在python中遍历目录以连接classpath变量
我编写了一个脚本,使用python连接一个名为在python中遍历目录以连接classpath变量,python,python-2.7,os.walk,Python,Python 2.7,Os.walk,我编写了一个脚本,使用python连接一个名为classpath\u augment的变量。我能够成功地将目录和包含的jar文件连接到classpath\u augment变量,但是,我还需要将包含.properties文件的目录添加到classpath变量 我该怎么做? 下面是我的代码: #! /usr/bin/env python import os import sys import glob java_command = "/myappsjava/home/bin/java -cla
classpath\u augment
的变量。我能够成功地将目录和包含的jar文件连接到classpath\u 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)
只需查找
.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
Umm
if.properties”在f:#添加我代码>?为什么classpath\u augment=':'。在循环之外加入(classpath)
?我需要将每个文件/目录条目分开classpath@ImtiazAhmad:你试过代码了吗?您只需要连接路径元素一次。classpath
列表在循环中扩展,一旦完成遍历,就生成最后一个字符串。@ImtiazAhmad:See<代码>“:”。join(类路径)
做你想做的事;将:
放在每个路径元素之间。好的,我知道了,谢谢。但有一个问题。如何连接包含.properties
文件的目录?另外请注意,我不希望目录与类路径连接两次。@ImtiazAhmad:目录只被遍历一次,因此它们只被添加一次。