我想从Python调用一个外部程序。我已经使用了Popen()
和call()
来做到这一点。
这两者有什么不同?
我的具体目标是从Python运行以下命令。我不确定重定向是如何工作的。
./my_script.sh > output
我读过the documentation,上面说call()
是一个方便函数或快捷函数。我们是否会因为使用call()
而不使用Popen()
而失去动力?
发布于 2011-10-07 07:59:09
有两种方法可以进行重定向。两者都适用于subprocess.Popen
或subprocess.call
。
shell = True
或executable = /path/to/the/shell
,并按原样指定命令。标准输出= an_open_writeable_file_object
对象指向output
文件的位置。
subprocess.Popen
比subprocess.call
更通用。
Popen
不会阻塞,允许您在进程运行时与其交互,或者继续执行您的Python程序中的其他操作。对Popen
的调用返回一个Popen
对象。
call
确实阻塞了。虽然它支持所有与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
进行了简单的包装。
发布于 2020-01-07 00:45:14
另一个答案非常完整,但这里有一个经验法则:
call
阻塞:closed
Popen
(‘notepad.exe’) print('hello') #仅当notepad为非阻塞时才执行:Popen('notepad.exe') print('hello') #立即执行
https://stackoverflow.com/questions/7681715
复制相似问题