2010-03-18 182 views
9

我需要从我的Python脚本执行这个脚本。如何从Python脚本调用可执行文件?

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

[email protected]:~/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 
+1

子过程是你需要使用的,你能提供一个例子,所以我们有一个更好的想法,为什么它不工作? – 2010-03-18 22:08:23

+0

“子流程调用”?那是什么?请发布您使用的代码和您实际得到的错误。 – 2010-03-18 22:51:04

+0

是的,他正在谈论标准“subprocess”模块中的“调用”功能,尽管os.system可能足以满足他的需要 – 2010-03-19 01:37:54

回答

23

为了执行外部程序,做到这一点:

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

+0

嗨,彼得,有错误:bin/bar:bin/bar:无法执行二进制文件,也没有来自Python运行时的任何其他信息。原因是什么? – 2010-03-19 11:51:00

+0

这是关于可执行文件的错误。我已经解决了,谢谢彼得。 – 2010-03-20 17:29:07

11

最简单的方法是:

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

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

如果您需要进行更复杂的子流程管理,那么subprocess模块就可以了。

相关问题