1. 程式人生 > >如何使用Python執行系統命令方法?老男孩IT教育

如何使用Python執行系統命令方法?老男孩IT教育

Python培訓 Python開發 Python學習

如何使用Python執行系統命令方法?老男孩IT教育

  Python是一款操作簡單的編程語言,內置豐富的庫,能夠很容易的實現強大的功能,在使用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

  

  >>> print output.read()

  processor : 0

  vendor_id : AuthenticAMD

  cpu family : 21

  ... ...

  >>>

  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"]) # python2.x doesn‘t capture output

  >>> subprocess.run(["ls", "-l"]) # python3.x doesn‘t capture output

  

  >>> 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執行系統命令的方法,如果需要這方面的操作,可以參考一下!

如何使用Python執行系統命令方法?老男孩IT教育