【问题标题】:How to make a call to an executable from Python script?如何从 Python 脚本调用可执行文件?
【发布时间】:2011-01-29 05:47:28
【问题描述】:

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

【问题讨论】:

  • subprocess 是您需要使用的,您能否提供一个示例以便我们更好地了解它为什么不起作用?
  • “子进程调用”?那是什么?请发布您使用的代码和您实际遇到的错误。
  • 是的,他说的是标准“子进程”模块中的“调用”函数,这是更好的方法,尽管 os.system 可能根据他的需要就足够了
  • 嗨 Kaleb,我编辑了这个问题。

标签: python linux executable system-calls


【解决方案1】:

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

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 程序,而无需在两者之间访问磁盘。

【讨论】:

  • 嗨彼得,有错误:bin/bar:bin/bar:无法执行二进制文件并且没有来自 Python 运行时的任何其他信息。是什么原因?
  • 这是关于可执行文件的错误。我已经解决了,谢谢彼得。
【解决方案2】:

最简单的方法是:

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

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

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

【讨论】:

  • 请注意,这与subprocess.Popen(shell=True) 具有相同的安全警告。请勿将其与文字字符串以外的任何内容一起使用。
  • 我想对我文件夹中的每个文件执行tesseract,所以我 os.walk 然后在循环中执行 progr。它是如何工作的?
【解决方案3】:

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

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

这里print so 输出结果。

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多