这里使用的版本:Python2 >= 2.7
对于获取命令行窗口中的输出python有一个很好用的模块:
两个简单例子:
1.获取ping命令的输出:
from subprocess import *
host = raw_input('输入一个主机地址:')
p = Popen(['ping', '-c5', host],
stdin=PIPE,
stdout=PIPE,
)
p.wait()
out = p.stdout.read()
print out
这里我之前一直是这样用的:
p = Popen(['ping', '-c5', host],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
shell=True
)
但这样写就怎么都获取不到到任何输出:
原因就是官方提醒过的:If shell is True, the specified command will be executed through the shell.
所以去掉就好了:
2.获取磁盘信息:
# -*- coding:utf-8 -*-
from subprocess import *
p = Popen('df -Th',
stdout=PIPE,
stderr=PIPE,
shell=True
)
p.wait()
out = p.stdout.read()
print out
可以看到又用shell=Ture了,这里如果不用,又会报错。该例子来自:https://www.cnblogs.com/yyds/p/7288916.html
参考资料:
1.https://docs.python.org/2/library/subprocess.html
2.https://www.cnblogs.com/yyds/p/7288916.html
3.https://blog.youkuaiyun.com/sophia_slr/article/details/44450739