有两种方法可以进行重定向。两者都适用于subprocess.Popen 或subprocess.call。
设置关键字参数shell = True 或executable = /path/to/the/shell 并指定命令,就像你在那里一样。
-
由于您只是将输出重定向到文件,因此请设置关键字参数
stdout = 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 周围的薄包装。