2015-08-19 40 views

回答

1

是的,可能的話,如果需要,您可以在自己的功能中添加該功能(只有在您需要它時才提供反向功能)。

if 'check_output' not in dir(subprocess): 
    def check_output(cmd_args, *args, **kwargs): 
     proc = subprocess.Popen(
      cmd_args, *args, 
      stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs) 
     out, err = proc.communicate() 
     if proc.returncode != 0: 
      raise subprocess.CalledProcessError(args) 
     return out 
    subprocess.check_output = check_output 

但是,正如該代碼所示,您也可以將其寫得更詳細一點,它的操作也不會有所不同。

編輯:直接從子模塊的Python版本2.7

def check_output(*popenargs, **kwargs): 
    if 'stdout' in kwargs: 
     raise ValueError('stdout argument not allowed, it will be overridden.') 
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) 
    output, unused_err = process.communicate() 
    retcode = process.poll() 
    if retcode: 
     cmd = kwargs.get("args") 
     if cmd is None: 
      cmd = popenargs[0] 
     raise subprocess.CalledProcessError(retcode, cmd, output=output) 
    return output 
+0

副本,以便將做同樣的事情,原來的功能? –

+0

實際上是的,如果你想使用它,我還包含了來自最新版本的子過程模塊的直接副本。再次,我只會將它用作現有代碼的向後兼容性。如果你正在編寫新的代碼,我會自己使用Popen和.communicate()。 – CasualDemon

+0

我爲這個項目使用了Python 2.6,這個代碼還能工作嗎? @CasualDemon –