前言
Python經常被稱作“膠水語言”,因為它能夠輕易地操作其他程序,輕易地包裝使用其他語言編寫的庫。在Python/wxPython環境下,執行外部命令或者說在Python程序中啟動另一個程序的方法。
本文將詳細介紹關于Python中如何執行系統命令的相關資料,下面話不多說了,來一起看看詳細的介紹吧。
(1) os.system()
這個方法直接調用標準C的system()函數,僅僅在一個子終端運行系統命令,而不能獲取執行返回的信息。
>>> import os >>> output = os.system('cat /proc/cpuinfo') processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> output # doesn't capture output 0 (2) os.popen()
這個方法執行命令并返回執行后的信息對象,是通過一個管道文件將結果返回。
>>> output = os.popen('cat /proc/cpuinfo') >>> output <open file 'cat /proc/cpuinfo', mode 'r' at 0x7ff52d831540> >>> print output.read() processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>><span style="font-size:14px;"> (3) commands模塊
>>> import commands >>> (status, output) = commands.getstatusoutput('cat /proc/cpuinfo') >>> print output processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> print status 0注意1:在類unix的系統下使用此方法返回的返回值(status)與腳本或命令執行之后的返回值不等,這是因為調用了os.wait()的緣故,具體原因就得去了解下系統wait()的實現了。需要正確的返回值(status),只需要對返回值進行右移8位操作就可以了。
注意2:當執行命令的參數或者返回中包含了中文文字,那么建議使用subprocess。
(4) subprocess模塊
該模塊是一個功能強大的子進程管理模塊,是替換os.system, os.spawn*等方法的一個模塊。
>>> import subprocess >>> subprocess.Popen(["ls", "-l"]) <strong> # python2.x</strong> doesn't capture output >>> subprocess.run(["ls", "-l"]) <strong># python3.x</strong> doesn't capture output <subprocess.Popen object at 0x7ff52d7ee490> >>> total 68 drwxrwxr-x 3 xl xl 4096 Feb 8 05:00 com drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Desktop drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Documents drwxr-xr-x 2 xl xl 4096 Jan 21 07:44 Downloads ... ... >>>
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答