Python—執行系統命令的四種方法(os.system、os.popen、commands、subprocess)

1、os.system方法

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

os.system(cmd)的返回值。若是執行成功,那麼會返回0,表示命令執行成功。不然,則是執行錯誤。linux

使用os.system返回值是腳本的退出狀態碼,該方法在調用完shell腳本後,返回一個16位的二進制數,低位爲殺死所調用腳本的信號號碼,高位爲腳本的退出狀態碼。shell

os.system()返回值爲0        linux命令返回值也爲0。函數

os.system()返回值爲256,十六位二進制數示爲:00000001,00000000,高八位轉成十進制爲 1        對應   linux命令返回值 1。spa

os.system()返回值爲512,十六位二進制數示爲:00000010,00000000,高八位轉成十進制爲 2        對應   linux命令返回值 2。.net

import os
result = os.system('cat /etc/passwd')
print(result)      # 0

2、os.popen方法

os.popen()方法不只執行命令並且返回執行後的信息對象(經常使用於須要獲取執行命令後的返回信息),是經過一個管道文件將結果返回。經過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操做能夠看到執行的輸出。code

import os
result = os.popen('cat /etc/passwd')
print(result.read())

3、commands模塊

import commands

status = commands.getstatus('cat /etc/passwd')
print(status)
output = commands.getoutput('cat /etc/passwd')
print(output)
(status, output) = commands.getstatusoutput('cat /etc/passwd')
print(status, output)

4、subprocess模塊

Subprocess是一個功能強大的子進程管理模塊,是替換os.system ,os.spawn* 等方法的一個模塊。htm

當執行命令的參數或者返回中包含了中文文字,那麼建議使用subprocess。對象

import subprocess
res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # 使用管道
# print res.stdout.read()  # 標準輸出
for line in res.stdout.readlines():
    print line
res.stdout.close()         # 關閉

5、總結:

os.system:獲取程序執行命令的返回值。blog

os.popen: 獲取程序執行命令的輸出結果。

commands:獲取返回值和命令的輸出結果。

https://www.jb51.net/article/142787.htm

相關文章
相關標籤/搜索