如何从Python脚本呼叫可执行文件?

2024-04-23 23:53:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件texttxt脚本binfooubuntubar
3条回答

最简单的方法是:

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

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

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

用于执行unix可执行文件。我在我的Mac操作系统中做了以下几点,这对我很有用:

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

这里print so输出结果。

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

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程序,而不必在两者之间插入磁盘。

相关问题 更多 >