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