【发布时间】:2014-06-06 01:11:18
【问题描述】:
我正在尝试确定使用 python 在命令行中执行某些操作的最佳方式。我已经在单个文件上使用subprocess.Popen() 完成了这项工作。但是,我正在尝试确定使用许多不同文件多次执行此操作的最佳方法。我不确定我是否应该创建一个批处理文件然后在命令中执行它,或者我是否只是在我的代码中遗漏了一些东西。新手编码员在这里,所以我提前道歉。下面的脚本在我使用循环时返回返回码 1,但在不在循环中时返回 0。手头任务的最佳方法是什么?
def check_output(command, console):
if console == True:
process = subprocess.Popen(command)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
output, error = process.communicate()
returncode = process.poll()
return returncode, output, error
for file in fileList.split(";"):
...code to create command string...
returncode, output, error = check_output(command, False)
if returncode != 0:
print("Process failed")
sys.exit()
编辑:示例命令字符串如下所示:
C:\Path\to\executable.exe -i C:\path\to\input.ext -o C:\path\to\output.ext
【问题讨论】:
-
你想完成什么?运行一堆命令并将它们的输出输入 Python?将每个命令链接在一起?并行运行它们?
-
按顺序运行它们,文件 1,文件 2,...我有一个可执行文件,我想在多个文件上运行,一次一个。
-
我们能否获得一个示例,说明当命令字符串被传递到
check_output时的样子?除了 Popen (stder) 中的一个错字之外,我看不出它有任何失败的原因。 -
使用子进程的内置 check_output 方法进行错误检查
-
@wils484,process.communicate() 错误返回 None。
标签: python windows loops python-2.7 popen