有时执行dos命令需要保存返回值

需要导入库subprocess

import subprocess

p = subprocess.Popen('ping www.baidu.com', shell=True, stdout=subprocess.PIPE)
out, err = p.communicate()
print out.splitlines()[24:27]
for line in out.splitlines():
print line

splitlines 是个列表

可以切片操作

完整代码:

# 利用python的subprocess模块执行外部命令, 并捕获stdout, stderr的输出:
# 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

输出:

Standard Output:
Standard Error: 'ls' 不是内部或外部命令,也不是可运行的程序
或批处理文件。 Process finished with exit code 0

部分内容来自网络

04-24 17:36