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

时间:2010-03-18 22:06:08

标签: python linux executable system-calls

我需要从我的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

3 个答案:

答案 0 :(得分:28)

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

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程序而不需要在它们之间使用磁盘。

答案 1 :(得分:12)

最简单的方法是:

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

您可以使用open()

以通常的方式访问文件

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

答案 2 :(得分:6)

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

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

此处print so输出结果。