python学习 —— 使用subprocess获取命令行输出结果

本文介绍了Python中使用subprocess模块来获取命令行输出的方法。通过示例展示了如何正确使用shell参数,以避免无法获取输出的问题。并提供了获取ping命令输出和磁盘信息的代码示例,同时列出了相关参考资料。

  这里使用的版本: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

转载于:https://www.cnblogs.com/darkchii/p/9013673.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值