如何从Python脚本调用可执行文件?

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

可能吗? 该脚本会生成一些输出,其中有些文件正在写入。 我如何访问这些文件? 我已经尝试过使用subprocess调用函数,但没有成功。

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

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

谢谢,

编辑:

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

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

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

 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程序,而不需要在两者之间的磁盘。

最简单的方法是:

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

您可以通过使用open()以通常的方式访问这些文件。

如果你需要做更复杂的子流程管理,那么子流程模块就是要走的路。