Python subprocess模塊常見用法分析
本文實例講述了Python subprocess模塊常見用法。分享給大家供大家參考,具體如下:
subprocess模塊是python從2.4版本開始引入的模塊。主要用來取代 一些舊的模塊方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通過子進(jìn)程來執(zhí)行外部指令,并通過input/output/error管道,獲取子進(jìn)程的執(zhí)行的返回信息。
常用方法:
subprocess.call()
:執(zhí)行命令,并返回執(zhí)行狀態(tài),其中shell參數(shù)為False時,命令需要通過列表的方式傳入,當(dāng)shell為True時,可直接傳入命令
示例如下:
>>> a = subprocess.call(['df','-hT'],shell=False) Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G 64G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot >>> a = subprocess.call('df -hT',shell=True) Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G 64G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot >>> print a 0
subprocess.check_call()
:用法與subprocess.call()
類似,區(qū)別是,當(dāng)返回值不為0時,直接拋出異常
示例:
>>> a = subprocess.check_call('df -hT',shell=True) Filesystem Type Size Used Avail Use% Mounted on /dev/sda2 ext4 94G 64G 26G 72% / tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm /dev/sda1 ext4 976M 56M 853M 7% /boot >>> print a 0 >>> a = subprocess.check_call('dfdsf',shell=True) /bin/sh: dfdsf: command not found Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127
subprocess.check_output()
:用法與上面兩個方法類似,區(qū)別是,如果當(dāng)返回值為0時,直接返回輸出結(jié)果,如果返回值不為0,直接拋出異常。需要說明的是,該方法在python3.x中才有。
subprocess.Popen()
:
在一些復(fù)雜場景中,我們需要將一個進(jìn)程的執(zhí)行輸出作為另一個進(jìn)程的輸入。在另一些場景中,我們需要先進(jìn)入到某個輸入環(huán)境,然后再執(zhí)行一系列的指令等。這個時候我們就需要使用到suprocess的Popen()
方法。該方法有以下參數(shù):
args:shell命令,可以是字符串,或者序列類型,如list,tuple。
bufsize:緩沖區(qū)大小,可不用關(guān)心
stdin,stdout,stderr:分別表示程序的標(biāo)準(zhǔn)輸入,標(biāo)準(zhǔn)輸出及標(biāo)準(zhǔn)錯誤
shell:與上面方法中用法相同
cwd:用于設(shè)置子進(jìn)程的當(dāng)前目錄
env:用于指定子進(jìn)程的環(huán)境變量。如果env=None,則默認(rèn)從父進(jìn)程繼承環(huán)境變量
universal_newlines:不同系統(tǒng)的的換行符不同,當(dāng)該參數(shù)設(shè)定為true時,則表示使用\n作為換行符
示例1,在/root下創(chuàng)建一個suprocesstest的目錄:
>>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root')
示例2,使用python執(zhí)行幾個命令:
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) obj.stdin.write('print 1 \n') obj.stdin.write('print 2 \n') obj.stdin.write('print 3 \n') obj.stdin.write('print 4 \n') obj.stdin.close() cmd_out = obj.stdout.read() obj.stdout.close() cmd_error = obj.stderr.read() obj.stderr.close() print cmd_out print cmd_error
也可以使用如下方法:
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) obj.stdin.write('print 1 \n') obj.stdin.write('print 2 \n') obj.stdin.write('print 3 \n') obj.stdin.write('print 4 \n') out_error_list = obj.communicate() print out_error_list
示例3,將一個子進(jìn)程的輸出,作為另一個子進(jìn)程的輸入:
import subprocess child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE) child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE) out = child2.communicate()
其他方法:
import subprocess child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE) child.poll() #檢查子進(jìn)程狀態(tài) child.kill() #終止子進(jìn)程 child.send_signal() #向子進(jìn)程發(fā)送信號 child.terminate() #終止子進(jìn)程
更多關(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)文章
Python中類型關(guān)系和繼承關(guān)系實例詳解
這篇文章主要介紹了Python中類型關(guān)系和繼承關(guān)系,較為詳細(xì)的分析了Python中類型關(guān)系和繼承關(guān)系的原理與使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-05-05python腳本監(jiān)控Tomcat服務(wù)器的方法
這篇文章主要介紹了利用python腳本監(jiān)控Tomcat服務(wù)器的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07Python Pandas常用函數(shù)方法總結(jié)
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Pandas常用函數(shù)方法展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06python中利用await關(guān)鍵字如何等待Future對象完成詳解
為了簡化并更好地標(biāo)識異步IO,從Python 3.5開始引入了新的語法async和await,可以讓coroutine的代碼更簡潔易讀。下面這篇文章主要給大家介紹了關(guān)于python中利用await關(guān)鍵字如何等待Future對象完成的相關(guān)資料,需要的朋友可以參考下。2017-09-09Python?ArcPy實現(xiàn)批量對大量遙感影像相減做差
這篇文章主要為大家介紹了如何基于Python中ArcPy模塊實現(xiàn)對大量柵格遙感影像文件批量進(jìn)行相減做差,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-06-06