Python subprocess模塊功能與常見用法實(shí)例詳解
本文實(shí)例講述了Python subprocess模塊功能與常見用法。分享給大家供大家參考,具體如下:
一、簡介
subprocess最早在2.4版本引入。用來生成子進(jìn)程,并可以通過管道連接他們的輸入/輸出/錯誤,以及獲得他們的返回值。
subprocess用來替換多個舊模塊和函數(shù):
- os.system
- os.spawn*
- os.popen*
- popen2.*
- commands.*
運(yùn)行python的時候,我們都是在創(chuàng)建并運(yùn)行一個進(jìn)程,linux中一個進(jìn)程可以fork一個子進(jìn)程,并讓這個子進(jìn)程exec另外一個程序。在python中,我們通過標(biāo)準(zhǔn)庫中的subprocess包來fork一個子進(jìn)程,并且運(yùn)行一個外部的程序。subprocess包中定義有數(shù)個創(chuàng)建子進(jìn)程的函數(shù),這些函數(shù)分別以不同的方式創(chuàng)建子進(jìn)程,所欲我們可以根據(jù)需要來從中選取一個使用。另外subprocess還提供了一些管理標(biāo)準(zhǔn)流(standard stream)和管道(pipe)的工具,從而在進(jìn)程間使用文本通信。
二、舊有模塊的使用
1.os.system()
執(zhí)行操作系統(tǒng)的命令,將結(jié)果輸出到屏幕,只返回命令執(zhí)行狀態(tài)(0:成功,非 0 : 失敗)
import os >>> a = os.system("df -Th") Filesystem Type Size Used Avail Use% Mounted on /dev/sda3 ext4 1.8T 436G 1.3T 26% / tmpfs tmpfs 16G 0 16G 0% /dev/shm /dev/sda1 ext4 190M 118M 63M 66% /boot >>> a 0 # 0 表示執(zhí)行成功 # 執(zhí)行錯誤的命令 >>> res = os.system("list") sh: list: command not found >>> res 32512 # 返回非 0 表示執(zhí)行錯誤
2. os.popen()
執(zhí)行操作系統(tǒng)的命令,會將結(jié)果保存在內(nèi)存當(dāng)中,可以用read()
方法讀取出來
import os >>> res = os.popen("ls -l") # 將結(jié)果保存到內(nèi)存中 >>> print res <open file 'ls -l', mode 'r' at 0x7f02d249c390> # 用read()讀取內(nèi)容 >>> print res.read() total 267508 -rw-r--r-- 1 root root 260968 Jan 27 2016 AliIM.exe -rw-------. 1 root root 1047 May 23 2016 anaconda-ks.cfg -rw-r--r-- 1 root root 9130958 Nov 18 2015 apache-tomcat-8.0.28.tar.gz -rw-r--r-- 1 root root 0 Oct 31 2016 badblocks.log drwxr-xr-x 5 root root 4096 Jul 27 2016 certs-build drwxr-xr-x 2 root root 4096 Jul 5 16:54 Desktop -rw-r--r-- 1 root root 2462 Apr 20 11:50 Face_24px.ico
三、subprocess模塊
1、subprocess.run()
>>> import subprocess # python 解析則傳入命令的每個參數(shù)的列表 >>> subprocess.run(["df","-h"]) Filesystem Size Used Avail Use% Mounted on /dev/mapper/VolGroup-LogVol00 289G 70G 204G 26% / tmpfs 64G 0 64G 0% /dev/shm /dev/sda1 283M 27M 241M 11% /boot CompletedProcess(args=['df', '-h'], returncode=0) # 需要交給Linux shell自己解析,則:傳入命令字符串,shell=True >>> subprocess.run("df -h|grep /dev/sda1",shell=True) /dev/sda1 283M 27M 241M 11% /boot CompletedProcess(args='df -h|grep /dev/sda1', returncode=0)
2、subprocess.call()
執(zhí)行命令,返回命令的結(jié)果和執(zhí)行狀態(tài),0或者非0
>>> res = subprocess.call(["ls","-l"]) 總用量 28 -rw-r--r-- 1 root root 0 6月 16 10:28 1 drwxr-xr-x 2 root root 4096 6月 22 17:48 _1748 -rw-------. 1 root root 1264 4月 28 20:51 anaconda-ks.cfg drwxr-xr-x 2 root root 4096 5月 25 14:45 monitor -rw-r--r-- 1 root root 13160 5月 9 13:36 npm-debug.log # 命令執(zhí)行狀態(tài) >>> res 0
3、subprocess.check_call()
執(zhí)行命令,返回結(jié)果和狀態(tài),正常為0 ,執(zhí)行錯誤則拋出異常
>>> subprocess.check_call(["ls","-l"]) 總用量 28 -rw-r--r-- 1 root root 0 6月 16 10:28 1 drwxr-xr-x 2 root root 4096 6月 22 17:48 _1748 -rw-------. 1 root root 1264 4月 28 20:51 anaconda-ks.cfg drwxr-xr-x 2 root root 4096 5月 25 14:45 monitor -rw-r--r-- 1 root root 13160 5月 9 13:36 npm-debug.log 0 >>> subprocess.check_call(["lm","-l"]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.7/subprocess.py", line 537, in check_call retcode = call(*popenargs, **kwargs) File "/usr/lib64/python2.7/subprocess.py", line 524, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
4、subprocess.getstatusoutput()
接受字符串形式的命令,返回 一個元組形式的結(jié)果,第一個元素是命令執(zhí)行狀態(tài),第二個為執(zhí)行結(jié)果
#執(zhí)行正確 >>> subprocess.getstatusoutput('pwd') (0, '/root') #執(zhí)行錯誤 >>> subprocess.getstatusoutput('pd') (127, '/bin/sh: pd: command not found')
5、subprocess.getoutput()
接受字符串形式的命令,放回執(zhí)行結(jié)果
>>> subprocess.getoutput('pwd') '/root'
6、subprocess.check_output()
執(zhí)行命令,返回執(zhí)行的結(jié)果,而不是打印
>>> res = subprocess.check_output("pwd") >>> res b'/root\n' # 結(jié)果以字節(jié)形式返回
四、subprocess.Popen()
其實(shí)以上subprocess使用的方法,都是對subprocess.Popen的封裝,下面我們就來看看這個Popen方法。
1、stdout
標(biāo)準(zhǔn)輸出
>>> res = subprocess.Popen("ls /tmp/yum.log", shell=True, stdout=subprocess.PIPE) # 使用管道 >>> res.stdout.read() # 標(biāo)準(zhǔn)輸出 b'/tmp/yum.log\n' res.stdout.close() # 關(guān)閉
2、stderr
標(biāo)準(zhǔn)錯誤
>>> import subprocess >>> res = subprocess.Popen("lm -l",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) # 標(biāo)準(zhǔn)輸出為空 >>> res.stdout.read() b'' #標(biāo)準(zhǔn)錯誤中有錯誤信息 >>> res.stderr.read() b'/bin/sh: lm: command not found\n'
注意:上面的提到的標(biāo)準(zhǔn)輸出都為啥都需要等于subprocess.PIPE,這個又是啥呢?原來這個是一個管道,這個需要畫一個圖來解釋一下:
4、poll()
定時檢查命令有沒有執(zhí)行完畢,執(zhí)行完畢后返回執(zhí)行結(jié)果的狀態(tài),沒有執(zhí)行完畢返回None
>>> res = subprocess.Popen("sleep 10;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> print(res.poll()) None >>> print(res.poll()) None >>> print(res.poll()) 0
5、wait()
等待命令執(zhí)行完成,并且返回結(jié)果狀態(tài)
>>> obj = subprocess.Popen("sleep 10;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> obj.wait() # 中間會一直等待 0
6、terminate()
結(jié)束進(jìn)程
import subprocess >>> res = subprocess.Popen("sleep 20;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> res.terminate() # 結(jié)束進(jìn)程 >>> res.stdout.read() b''
7、pid
獲取當(dāng)前執(zhí)行子shell的程序的進(jìn)程號
import subprocess >>> res = subprocess.Popen("sleep 5;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> res.pid # 獲取這個linux shell 的 進(jìn)程號 2778
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
如何解決django-celery啟動后迅速關(guān)閉
在本篇文章里小編給大家整理的是關(guān)于django-celery啟動后迅速關(guān)閉的解決方法,有需要的朋友們學(xué)習(xí)下。2019-10-10Python?遞歸式實(shí)現(xiàn)二叉樹前序,中序,后序遍歷
這篇文章主要介紹了Python?遞歸式實(shí)現(xiàn)二叉樹前序,中序,后序遍歷,更多相關(guān)資料,需要的小伙伴可以參考下面具體的文章內(nèi)容2022-03-03python接口自動化(十六)--參數(shù)關(guān)聯(lián)接口后傳(詳解)
這篇文章主要介紹了python接口自動化參數(shù)關(guān)聯(lián)接口,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04Python結(jié)合spaCy?進(jìn)行簡易自然語言處理
這篇文章主要為大家介紹了Python結(jié)合spaCy進(jìn)行簡易自然語言處理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06