四大Python執行系統命令方法

轉載請註明出處:www.oldboyedu.com

Python是一款操作簡單的編程語言,內置豐富的庫,能夠很容易的實現強大的功能,在使用Python進行框架搭建時,往往需要用到Python執行系統命令,一些開發人員對此不熟悉,以下是具體的操作方法:

1. os.system()

這個方法直接調用標準Csystem()函數,僅僅在一個子終端運行系統命令,而不能獲取執行返回的信息。

>>> 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

... ...

>>> 

以上是列舉的python執行系統命令的方法,如果需要這方面的操作,可以參考一下!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章