子流程Popen和call有什么区别(如何使用它们)?

发布于 2021-01-29 19:33:40

我想从Python调用一个外部程序。我已经用过Popen()并且call()做到了。

两者有什么区别?

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

./my_script.sh > output

我阅读了文档,并说它call()是便利功能或快捷功能。我们使用call()代替会失去任何功能Popen()吗?

关注者
0
被浏览
86
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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

      stdout = an_open_writeable_file_object
      

    对象指向output文件的位置。

    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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看