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


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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM