问题描述
我想从Python调用一个外部程序.我已经使用Popen()
和call()
来做到这一点.
I want to call an external program from Python. I have used both Popen()
and call()
to do that.
两者之间有什么区别?
我的特定目标是从Python运行以下命令.我不确定重定向的工作方式.
My specific goal is to run the following command from Python. I am not sure how redirects work.
./my_script.sh > output
我阅读了文档,它说call()
是一种便利功能,或者快捷功能.通过使用call()
而不是Popen()
会失去能量吗?
I read the documentation and it says that call()
is a convenience function or a shortcut function. Do we lose any power by using call()
instead of Popen()
?
推荐答案
有两种方法可以进行重定向.两者都适用于subprocess.Popen
或subprocess.call
.
There are two ways to do the redirect. Both apply to either subprocess.Popen
or subprocess.call
.
-
设置关键字参数
shell = True
或executable = /path/to/the/shell
并根据需要在其中指定命令.
Set the keyword argument
shell = True
orexecutable = /path/to/the/shell
and specify the command just as you have it there.
由于您只是将输出重定向到文件,因此请设置关键字参数
Since you're just redirecting the output to a file, set the keyword argument
stdout = an_open_writeable_file_object
对象指向output
文件的位置.
subprocess.Popen
比 subprocess.call
.
Popen
不会阻塞,允许您在进程运行时与它进行交互,或者继续执行Python程序中的其他操作.调用Popen
返回一个Popen
对象.
Popen
doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen
returns a Popen
object.
call
做块.它支持与Popen
构造函数相同的所有参数,因此您仍然可以设置进程的输出,环境变量等,脚本将等待程序完成,并且call
返回代表进程的代码.退出状态.
call
does block. While it supports all the same arguments as the Popen
constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call
returns a code representing the process' exit status.
returncode = call(*args, **kwargs)
与调用
returncode = Popen(*args, **kwargs).wait()
call
只是一个便捷功能.它在CPython中的实现位于 subprocess.py :
call
is just a convenience function. It's implementation in CPython is in subprocess.py:
def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
如您所见,它是围绕Popen
的薄包装.
As you can see, it's a thin wrapper around Popen
.
这篇关于子流程Popen和call有什么区别(我该如何使用它们)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!