0

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

我怎样才能做到这一点?
下面是我的代码:

#! /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)
4

1 回答 1

0

只需查找.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循环:

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

    for root, dirs, files in os.walk(project_dir):
        has_properties = False
        for f in files:
            if f.endswith('.jar'):
                classpath.append(os.path.join(root, f))
            if f.endswith('.properties'):
                has_properties = True
        if has_properties:
            classpath.append(root)

    classpath_augment = ':'.join(classpath)

    print java_command, classpath_augment, main_class, specific_args
于 2013-09-18T20:41:02.767 回答