Python中执行外部命令并捕获双向输出
原文:http://my.oschina.net/qihh/blog/74266
利用python的subprocess模块执行外部命令,并捕获stdout,stderr的输出:
利用python的subprocess模块执行外部命令,并捕获stdout,stderr的输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Python代码 import subprocess #print ’popen3:’ def external_cmd(cmd, msg_in=''): try: proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout_value, stderr_value = proc.communicate(msg_in) return stdout_value, stderr_value except ValueError as err: #log("ValueError: %s" % err) return None, None except IOError as err: #log("IOError: %s" % err) return None, None if __name__ == '__main__': stdout_val, stderr_val = external_cmd('ls -l') print 'Standard Output: %s' % stdout_val print 'Standard Error: %s' % stderr_val |