如何从 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
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
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()?
Thank you,
Edit:
The error from Python runtime is only this line.
$ python foo.py
bin/bar: bin/bar: cannot execute binary file
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要执行外部程序,请执行以下操作:
是的,假设您的 bin/bar 程序将一些其他分类文件写入磁盘,您可以使用 open("path/to/输出/file.txt")。请注意,如果您不愿意,则无需依赖子 shell 将输出重定向到磁盘上名为“output”的文件。我在这里展示了如何直接将输出读取到 python 程序中,而无需在中间读取磁盘。
For executing the external program, do this:
And yes, assuming your
bin/bar
program wrote some other assorted files to disk, you can open them as normal withopen("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.最简单的方法是:
使用
open()
以通常的方式访问文件。如果您需要进行更复杂的子流程管理,那么 subprocess 模块就是最佳选择。
The simplest way is:
You access the files in the usual way, by using
open()
.If you need to do more complicated subprocess management then the subprocess module is the way to go.
用于执行 unix 可执行文件。我在 Mac OSX 中执行了以下操作,它对我有用:
这里
print(so)
输出结果。For executing a unix executable file. I did the following in my Mac OSX and it worked for me:
Here
print(so)
outputs the result.