Linux 如何从 Python 脚本调用可执行文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2473655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a call to an executable from Python script?
提问by fx.
I need to execute this script from my Python script.
我需要从我的 Python 脚本中执行这个脚本。
Is it possible? The script generate some outputs with some files being written. How do I access these files? I have tried with subprocess call function but without success.
是否可以?该脚本生成一些输出并写入一些文件。我如何访问这些文件?我曾尝试使用子进程调用函数,但没有成功。
fx@fx-ubuntu:~/Documents/projects/foo$ bin/bar -c somefile.xml -d text.txt -r aString -f anotherString >output
The application "bar" also references to some libraries, it also create the file "bar.xml" besides the output. How do I get access to these files? Just by using open()?
应用程序“bar”还引用了一些库,除了输出之外,它还创建文件“bar.xml”。如何访问这些文件?仅仅通过使用 open()?
Thank you,
谢谢,
Edit:
编辑:
The error from Python runtime is only this line.
Python 运行时的错误只是这一行。
$ python foo.py
bin/bar: bin/bar: cannot execute binary file
采纳答案by Peter Lyons
For executing the external program, do this:
要执行外部程序,请执行以下操作:
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
And yes, assuming your bin/bar
program wrote some other assorted files to disk, you can open them as normal with open("path/to/output/file.txt")
. Note that you don't need to rely on a subshell to redirect the output to a file on disk named "output" if you don't want to. I'm showing here how to directly read the output into your python program without going to disk in between.
是的,假设您的bin/bar
程序将一些其他分类文件写入磁盘,您可以使用open("path/to/output/file.txt")
. 请注意,如果您不想,您不需要依赖子shell 将输出重定向到磁盘上名为“output”的文件。我在这里展示了如何将输出直接读入您的 python 程序,而无需在两者之间访问磁盘。
回答by rz.
The simplest way is:
最简单的方法是:
import os
cmd = 'bin/bar --option --otheroption'
os.system(cmd) # returns the exit status
You access the files in the usual way, by using open()
.
您可以使用通常的方式访问文件open()
。
If you need to do more complicated subprocess management then the subprocessmodule is the way to go.
如果您需要进行更复杂的子流程管理,那么子流程模块是您的最佳选择。
回答by Sumesh Chandran
For executing a unix executable file. I did the following in my Mac OSX and it worked for me:
用于执行 unix 可执行文件。我在 Mac OSX 中执行了以下操作,它对我有用:
import os
cmd = './darknet classifier predict data/baby.jpg'
so = os.popen(cmd).read()
print so
Here print so
outputs the result.
这里print so
输出结果。