如何在python中的文件目录上运行UNIX命令时修复"'bool' object is not iterable"错误



我正试图使用python通过UNIX可执行文件运行目录中的文件列表。我会将每个文件的可执行文件的输出写入不同的目录,但保留原始文件名。

我使用的是python 2.7,所以使用subprocess.call方法。我收到一个错误,说"‘ool’对象不可迭代",我猜这是由于我试图编写输出文件的部分,因为当我通过控制台运行以下脚本时,我在控制台窗口中得到了特定于可执行文件的预期输出:

import subprocess
import os
for inp in os.listdir('/path/to/input/directory/'):
subprocess.call(['/path/to/UNIX/executable', inp])

我的代码目前是这样的:

import subprocess
import os
for inp in os.listdir('/path/to/input/directory/'):
out = ['/path/to/output/directory/%s' % inp]
subprocess.call(['/path/to/UNIX/executable', inp] > out)

然而,第二批代码返回了"‘pool’不可迭代"错误。

我猜这个解决方案很琐碎,因为它不是一个复杂的任务。然而,作为一个初学者,我不知道从哪里开始!

解决:按照@barak itkin的回答,对于那些将来可能偶然发现这个问题的人,代码使用以下方法成功运行:

import subprocess
import os
for inp in os.listdir('/path/to/input/directory/'):
with open('/path/to/output/directory/%s' % inp, 'w') as out_file:
subprocess.call(['/path/to/UNIX/executable', inp], stdout=out_file)

要将子进程.call的输出写入文件,您需要使用> path/to/out作为命令本身的一部分,或者通过指定输出应指向的文件来"正确"执行此操作:

# Option 1:
# Specify that the command is using a "shell" syntax, meaning that
# things like output redirection (such as with ">") should be handled
# by the shell that will evaluate the command
subprocess.call('my_command arg1 arg2 > /path/to/out', shell=True)
# Option 2:
# Open the file to which you want to write the output, and then specify
# the `stdout` parameter to be that file
with open('/path/to/out', 'w') as out_file:
subprocess.call(['my_command', 'arg1', 'arg2'], stdout=out_file)

这对你有用吗?

相关内容

最新更新