2015-12-18 24 views
1

我必须写一个Python代码为我的生产服务器,因此尝试通过一个例子来清除我的概念。 Python脚本必须调用并执行bash shell脚本 - shell脚本可能会转储大量消息并退出成功或退出(2)系统调用。因此,我通过以下方法尝试:获取独立的变量stderr和标准输出与退出状态

import subprocess 
try: 
     output = subprocess.check_output(
       'bash mytest', 
      shell=True, 
      stderr=subprocess.STDOUT, 
     ) 
     print 'Have %d bytes in output' % len(output) 
     print output 
except subprocess.CalledProcessError, e: 
     print "Error String:", e.output 
     print "Error Return code:", e.returncode 

的代码工作正常,但它是调用鉴于该脚本可以(使用echo)打印数百行的正确途径。

将输出变量兼得stderr和标准输出消息通过bash脚本印?我可以在单独的变量中获得bash脚本的stderr和stdout消息 - 请记住,如果脚本成功运行,可能根本没有任何stderr消息?

此外,我应该承担的情况下,异常subprocess.CalledProcessError没有抛出的返回码0(成功)?

是否有实现相同的一个更好的办法 - 将这种方法确保Python脚本会等到bash脚本的完成?

在此先感谢。

+0

请阅读[本教程(https://pymotw.com/2/subprocess/)上PMOTW – Pynchia

+0

和[此SO Q&A]( http://stackoverflow.com/questions/5631624/how-to-get-exit-code-when-using-python-subprocess-communicate-method) – Pynchia

回答

0

如果你想同时捕获stdoutstderr你必须使用一个低级别的功能。扩大对check_output的源代码,这里是你可以做什么:

process = Popen(stdout=PIPE, stderr=PIPE, *popenargs, **kwargs) 
output, stderr = process.communicate() 
retcode = process.poll() 
if retcode: 
    cmd = kwargs.get("args") 
    if cmd is None: 
     cmd = popenargs[0] 
    raise CalledProcessError(retcode, cmd, output=stderr) # or your own exception 
return output 
相关问题