2011-10-06 15 views
126

我想从Python调用外部程序。我用Popen()call()来做到这一点。子进程Popen和调用之间有什么区别(我该如何使用它们)?

两者有什么区别?

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

./my_script.sh > output 

我读the documentation和它说,call()是一个方便的功能或快捷功能。我们是否通过使用call()而不是Popen()失去了任何权力?

+0

文档的哪些部分让您困惑? 'call()'的定义似乎很清楚。你能提供一个报价或一个链接,所以我们知道在回答中需要关注什么? –

回答

188

有两种方法可以进行重定向。两者适用于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相同的参数,但仍然可以设置进程的输出,环境变量等,脚本将等待程序完成,并返回代表进程退出状态的代码。

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瘦包装。

+7

基本上Popen和call是分别用异步和同步函数运行的Linux命令。 – user3016020

+1

使用popen的优点是什么?等到被调用的程序第一次完成后不是安全的吗? – Tom

+3

@汤姆通常不会。如果你想读取一些输出,然后发送更多的输入到程序,读取输入的更多输出,重复? – agf

相关问题