python - 子进程 Popen 和 call 有什么区别(我该如何使用它们)?

我想从 Python 调用一个外部程序。我已经使用了 Popen()call() 来做到这一点。

两者有什么区别?

我的具体目标是从 Python 运行以下命令。我不确定重定向是如何工作的。

./my_script.sh > output

我读过 the documentation它说 call() 是一个便利功能或快捷功能。我们是否会因为使用 call() 而不是 Popen() 而失去任何权力?

最佳答案

有两种方法可以进行重定向。两者都适用于 subprocess.Popensubprocess.call

  1. 设置关键字参数 shell = Trueexecutable =/path/to/the/shell 并指定命令,就像你在那里一样。

  2. 由于您只是将输出重定向到文件,请设置关键字参数

    stdout = an_open_writeable_file_object
    

    对象指向输出文件的位置。

subprocess.Popensubprocess.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 的薄包装。

https://stackoverflow.com/questions/7681715/

相关文章:

python - 在 Python 中循环列表

python - 在 Python 中使用 "continue"语句的示例?

c - 为什么需要 .bss 段?

python - 谁能解释python的相对进口?

linux - 获取后台进程的退出代码

linux - 如何获取终端的字符编码

python - 如何模拟请求和响应?

linux - Linux 的虚拟串行端口

linux - 如何在 Linux 上将行添加到文件末尾

python - 为什么 Python 的 math.ceil() 和 math.floor() 操