23

我需要从我的 Python 脚本中执行这个脚本。

可能吗?该脚本生成一些输出,其中包含一些正在写入的文件。如何访问这些文件?我尝试过使用子进程调用功能,但没有成功。

fx@fx-ubuntu:~/Documents/projects/foo$ bin/bar -c somefile.xml -d text.txt -r aString -f anotherString >output

应用程序“bar”还引用了一些库,除了输出之外,它还创建文件“bar.xml”。如何访问这些文件?仅仅通过使用 open()?

谢谢,

编辑:

Python 运行时的错误只是这一行。

$ python foo.py
bin/bar: bin/bar: cannot execute binary file
4

3 回答 3

46

要执行外部程序,请执行以下操作:

import subprocess
args = ("bin/bar", "-c", "somefile.xml", "-d", "text.txt", "-r", "aString", "-f", "anotherString")
#Or just:
#args = "bin/bar -c somefile.xml -d text.txt -r aString -f anotherString".split()
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
output = popen.stdout.read()
print output

是的,假设您的bin/bar程序将一些其他分类文件写入磁盘,您可以正常使用open("path/to/output/file.txt"). 请注意,如果您不想这样做,则不需要依赖子shell 将输出重定向到磁盘上名为“output”的文件。我在这里展示了如何直接将输出读入你的 python 程序,而无需在两者之间访问磁盘。

于 2010-03-19T01:47:04.100 回答
19

最简单的方法是:

import os
cmd = 'bin/bar --option --otheroption'
os.system(cmd) # returns the exit status

您以通常的方式访问文件,使用open().

如果您需要进行更复杂的子流程管理,那么子流程模块就是您的选择。

于 2010-03-18T22:17:18.557 回答
8

用于执行 unix 可执行文件。我在我的 Mac OSX 中执行了以下操作,它对我有用:

import os
cmd = './darknet classifier predict data/baby.jpg'
so = os.popen(cmd).read()
print so

这里print so输出结果。

于 2018-06-04T10:28:35.973 回答