如何从Python脚本调用可执行文件? [英] How to make a call to an executable from Python script?

查看:270
本文介绍了如何从Python脚本调用可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从我的Python脚本中执行该脚本.

I need to execute this script from my Python script.

有可能吗?该脚本会生成一些输出,并写入一些文件.如何访问这些文件?我尝试了子流程调用功能,但没有成功.

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

应用程序"bar"还引用了一些库,除了输出外,它还创建了文件"bar.xml".我如何访问这些文件?只是通过使用open()?

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()?

谢谢

Python运行时错误仅是这一行.

The error from Python runtime is only this line.

$ python foo.py
bin/bar: bin/bar: cannot execute binary file

推荐答案

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

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

是的,假设您的bin/bar程序将其他一些分类文件写入磁盘,则可以使用open("path/to/output/file.txt")正常打开它们.请注意,如果不需要,您不需要依赖子外壳将输出重定向到磁盘上名为"output"的文件.我在这里展示如何直接将输出读取到您的python程序中,而无需在它们之间插入磁盘.

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.

这篇关于如何从Python脚本调用可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆