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

这两者有什么区别?

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

./my_script.sh > output

我读了文档,它说call()是一个方便函数或快捷函数。使用call()而不是Popen()是否会失去任何功能?


当前回答

另一个答案非常完整,但这里有一个经验法则:

呼叫阻塞: 调用(“notepad.exe”) 仅在记事本关闭时执行Print ('hello') # Popen是非阻塞的: Popen(“notepad.exe”) Print ('hello') #立即执行

其他回答

重定向有两种方法。两者都适用于任一子流程。Popen或subprocess.call。

将关键字参数shell = True或executable = /path/设置为/the/shell,并指定命令。 因为您只是将输出重定向到一个文件,所以设置关键字参数 Stdout = an_open_writeable_file_object 对象指向输出文件的位置。

子流程。Popen比subprocess.call更通用。

Popen不会阻塞,允许你在进程运行时与它交互,或者继续你的Python程序中的其他事情。对Popen的调用返回一个Popen对象。

调用确实阻塞。虽然它支持与Popen构造函数相同的所有参数,因此您仍然可以设置进程的输出、环境变量等,但您的脚本等待程序完成,并调用返回表示进程退出状态的代码。

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的包装纸。

另一个答案非常完整,但这里有一个经验法则:

呼叫阻塞: 调用(“notepad.exe”) 仅在记事本关闭时执行Print ('hello') # Popen是非阻塞的: Popen(“notepad.exe”) Print ('hello') #立即执行