python中subprocess實(shí)例用法及知識(shí)點(diǎn)詳解
1、subprocess這個(gè)模塊來(lái)產(chǎn)生子進(jìn)程,并且可以連接到子進(jìn)程的標(biāo)準(zhǔn)輸入、輸出、錯(cuò)誤中,還可以獲得子進(jìn)程的返回值。
2、subprocess提供了2種方法調(diào)用子程序。
實(shí)例
# coding:utf-8 import os # popen返回文件對(duì)象,同open操作一樣 f = os.popen(r"ls", "r") l = f.read() print(l) f.close()
Python subprocess知識(shí)點(diǎn)擴(kuò)充
使用subprocess模塊的目的是用于替換os.system等一些舊的模塊和方法。
運(yùn)行python的時(shí)候,我們都是在創(chuàng)建并運(yùn)行一個(gè)進(jìn)程。像Linux進(jìn)程那樣,一個(gè)進(jìn)程可以fork一個(gè)子進(jìn)程,并讓這個(gè)子進(jìn)程exec另外一個(gè)程序。在Python中,我們通過(guò)標(biāo)準(zhǔn)庫(kù)中的subprocess包來(lái)fork一個(gè)子進(jìn)程,并運(yùn)行一個(gè)外部的程序。
subprocess包中定義有數(shù)個(gè)創(chuàng)建子進(jìn)程的函數(shù),這些函數(shù)分別以不同的方式創(chuàng)建子進(jìn)程,所以我們可以根據(jù)需要來(lái)從中選取一個(gè)使用。另外subprocess還提供了一些管理標(biāo)準(zhǔn)流(standard stream)和管道(pipe)的工具,從而在進(jìn)程間使用文本通信。
導(dǎo)入模塊
>>> import subprocess
命令執(zhí)行call()
執(zhí)行由參數(shù)提供的命令,把數(shù)組作為參數(shù)運(yùn)行命令。其功能類似于os.system(cmd)。
>>> subprocess.call(['ls','-l')
其中參數(shù)shell默認(rèn)為False。
在shell設(shè)置為True時(shí),可以直接傳字符串:
>>> subprocess.call('ls -l',shell=True)
獲得返回結(jié)果check_output()
call()是不返回顯示的結(jié)果的,可以使用check_ouput()來(lái)獲得返回的結(jié)果:
>>> result = subprocess.check_output(['ls','-l'],shell=True) >>> result.decode('utf-8')
進(jìn)程創(chuàng)建和管理Popen類
subprocess.popen代替os.popen??梢詣?chuàng)建一個(gè)Popen類來(lái)創(chuàng)建進(jìn)程和進(jìn)行復(fù)雜的交互。
創(chuàng)建不等待的子進(jìn)程
import subprocess child = subprocess.Popen(['ping','-c','4','www.baidu.com']) print('Finished')
添加子進(jìn)程等待
import subprocess child = subprocess.Popen(['ping','-c','4','www.baidu.com']) child.wait() # 等待子進(jìn)程結(jié)束 print('Finished')
添加了wait()后,主進(jìn)程會(huì)等待子進(jìn)程結(jié)束再執(zhí)行下面的語(yǔ)句。
子進(jìn)程文本流控制
標(biāo)準(zhǔn)輸出重定向:
import subprocess child = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE) #將標(biāo)準(zhǔn)輸出定向輸出到subprocess.PIPE print(child.stdout.read())
使用stdin與其配合使用:
import subprocess child1 = subprocess.Popen(['cat','/etc/passwd'],stdout=subprocess.PIPE) child2 = subprocess.Popen(['grep','root'],stdin=child1.stdout,stdout=subprocess.PIPE) print child2.communicate()
到此這篇關(guān)于python中subprocess實(shí)例用法及知識(shí)點(diǎn)詳解的文章就介紹到這了,更多相關(guān)python中subprocess的用法內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。