我想从Python调用一个外部程序.我用了Popen()
和call()
来做这件事.
这两者有什么区别?
我的具体目标是从Python运行以下命令.我不确定重定向是如何工作的.
./my_script.sh > output
我读了the documentation,它说call()
是一个便利功能或快捷功能.我们用call()
而不是Popen()
会失go 能量吗?
我想从Python调用一个外部程序.我用了Popen()
和call()
来做这件事.
这两者有什么区别?
我的具体目标是从Python运行以下命令.我不确定重定向是如何工作的.
./my_script.sh > output
我读了the documentation,它说call()
是一个便利功能或快捷功能.我们用call()
而不是Popen()
会失go 能量吗?
有两种方法可以重定向.两者都适用于subprocess.Popen
或subprocess.call
.
设置关键字参数shell = True
或executable = /path/to/the/shell
,并按原样指定命令.
因为您只是将输出重定向到一个文件,所以设置关键字参数
stdout = an_open_writeable_file_object
其中对象指向output
文件.
subprocess.Popen
比subprocess.call
更普遍.
不会挡路,允许您在进程运行时与其交互,或者继续执行Python程序中的其他操作.调用Popen
将返回一个Popen
对象.
call
does街区.虽然它支持与Popen
构造函数相同的所有参数,因此您仍然可以设置进程的输出、环境变量等,但您的脚本会等待程序完成,call
会返回表示进程退出状态的代码.
returncode = call(*args, **kwargs)
基本上和打电话一样
returncode = Popen(*args, **kwargs).wait()
call
只是一个方便的功能.它在CPython中的实现是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
个.