这里使用的版本:Python2 >= 2.7
对于获取命令行窗口中的输出python有一个很好用的模块:subprocess
两个简单例子:
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.csdn.net/sophia_slr/article/details/44450739
本文介绍了Python中使用subprocess模块来获取命令行输出的方法。通过示例展示了如何正确使用shell参数,以避免无法获取输出的问题。并提供了获取ping命令输出和磁盘信息的代码示例,同时列出了相关参考资料。
6645

被折叠的 条评论
为什么被折叠?



