在python中遍历目录以连接类路径变量

2024-04-26 12:12:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个脚本,用python连接一个名为classpath_augment的变量。我能够成功地将目录和包含的jar文件连接到classpath_augment变量,但是,我还需要将包含.properties文件的目录添加到classpath变量中。在

我怎么能做到呢?
以下是我的代码:

#! /usr/bin/env python

import os
import sys
import glob

java_command = "/myappsjava/home/bin/java -classpath "

def run(project_dir, main_class, specific_args):

        classpath_augment = ""

        for r, d, f in os.walk(project_dir):
                for files in f:
                        if (files.endswith(".jar")):
                                classpath_augment += os.path.join(r, files)+":"

        if (classpath_augment[-1] == ":"):
                classpath_augment = classpath_augment[:-1]

        args_passed_in = '%s %s %s %s' % (java_command, classpath_augment, main_class, specific_args)
        print args_passed_in
        #os.system(args_passed_in)

Tags: 文件inimport目录projectbinosargs
1条回答
网友
1楼 · 发布于 2024-04-26 12:12:58

只需查找.properties文件:

def run(project_dir, main_class, specific_args):
    classpath = []

    for root, dirs, files in os.walk(project_dir):
        classpath.extend(os.path.join(root, f) for f in files if f.endswith('.jar'))
        if any(f.endswith('.properties') for f in files):
            classpath.append(root)

    classpath_augment = ':'.join(classpath)

    print java_command, classpath_augment, main_class, specific_args

我在一定程度上简化了代码;首先使用列表收集所有类路径路径,然后使用str.join()创建最后一个字符串。这比逐个连接每个新路径要快。在

如果您使用的是非常旧的Python版本,并且any()尚不可用,请使用for循环:

^{pr2}$

相关问题 更多 >