您的当前位置:首页正文

python利用python的subprocess模块执行外部命令,获取返回值

来源:帮我找美食网
python利⽤python的subprocess模块执⾏外部命令,获取返回

有时执⾏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

部分内容来⾃⽹络

因篇幅问题不能全部显示,请点此查看更多更全内容

Top