python進(jìn)程類subprocess的一些操作方法例子
subprocess.Popen用來(lái)創(chuàng)建子進(jìn)程。
1)Popen啟動(dòng)新的進(jìn)程與父進(jìn)程并行執(zhí)行,默認(rèn)父進(jìn)程不等待新進(jìn)程結(jié)束。
def TestPopen():
import subprocess
p=subprocess.Popen("dir",shell=True)
for i in range(250) :
print ("other things")
2)p.wait函數(shù)使得父進(jìn)程等待新創(chuàng)建的進(jìn)程運(yùn)行結(jié)束,然后再繼續(xù)父進(jìn)程的其他任務(wù)。且此時(shí)可以在p.returncode中得到新進(jìn)程的返回值。
def TestWait():
import subprocess
import datetime
print (datetime.datetime.now())
p=subprocess.Popen("sleep 10",shell=True)
p.wait()
print (p.returncode)
print (datetime.datetime.now())
3) p.poll函數(shù)可以用來(lái)檢測(cè)新創(chuàng)建的進(jìn)程是否結(jié)束。
def TestPoll():
import subprocess
import datetime
import time
print (datetime.datetime.now())
p=subprocess.Popen("sleep 10",shell=True)
t = 1
while(t <= 5):
time.sleep(1)
p.poll()
print (p.returncode)
t+=1
print (datetime.datetime.now())
4) p.kill或p.terminate用來(lái)結(jié)束創(chuàng)建的新進(jìn)程,在windows系統(tǒng)上相當(dāng)于調(diào)用TerminateProcess(),在posix系統(tǒng)上相當(dāng)于發(fā)送信號(hào)SIGTERM和SIGKILL。
def TestKillAndTerminate():
p=subprocess.Popen("notepad.exe")
t = 1
while(t <= 5):
time.sleep(1)
t +=1
p.kill()
#p.terminate()
print ("new process was killed")
5) p.communicate可以與新進(jìn)程交互,但是必須要在popen構(gòu)造時(shí)候?qū)⒐艿乐囟ㄏ颉?/strong>
def TestCommunicate():
import subprocess
cmd = "dir"
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdoutdata, stderrdata) = p.communicate()
if p.returncode != 0:
print (cmd + "error !")
#defaultly the return stdoutdata is bytes, need convert to str and utf8
for r in str(stdoutdata,encoding='utf8' ).split("\n"):
print (r)
print (p.returncode)
def TestCommunicate2():
import subprocess
cmd = "dir"
#universal_newlines=True, it means by text way to open stdout and stderr
p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
curline = p.stdout.readline()
while(curline != ""):
print (curline)
curline = p.stdout.readline()
p.wait()
print (p.returncode)
6) call函數(shù)可以認(rèn)為是對(duì)popen和wait的分裝,直接對(duì)call函數(shù)傳入要執(zhí)行的命令行,將命令行的退出code返回。
def TestCall():
retcode = subprocess.call("c:\\test.bat")
print (retcode)
7)subprocess.getoutput 和 subprocess.getstatusoutput ,基本上等價(jià)于subprocess.call函數(shù),但是可以返回output,或者同時(shí)返回退出code和output。
但是可惜的是好像不能在windows平臺(tái)使用,在windows上有如下錯(cuò)誤:'{' is not recognized as an internal or external command, operable program or batch file.
def TestGetOutput():
outp = subprocess.getoutput("ls -la")
print (outp)
def TestGetStatusOutput():
(status, outp) = subprocess.getstatusoutput('ls -la')
print (status)
print (outp)
8)總結(jié)
popen的參數(shù),第一個(gè)為字符串(或者也可以為多個(gè)非命名的參數(shù)),表示你要執(zhí)行的命令和命令的參數(shù);后面的均為命名參數(shù);shell=True,表示你前面的傳入的命令將在shell下執(zhí)行,如果你的命令是個(gè)可執(zhí)行文件或bat,不需要指定此參數(shù);stdout=subprocess.PIPE用來(lái)將新進(jìn)程的輸出重定向,stderr=subprocess.STDOUT將新進(jìn)程的錯(cuò)誤輸出重定向到stdout,stdin=subprocess.PIPE用來(lái)將新進(jìn)程的輸入重定向;universal_newlines=True表示以text的方式打開stdout和stderr。
其他的不推薦使用的模塊:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
相關(guān)文章
在Django的模板中使用認(rèn)證數(shù)據(jù)的方法
這篇文章主要介紹了在Django的模板中使用認(rèn)證數(shù)據(jù)的方法,Django是最具人氣的Python web開發(fā)框架,需要的朋友可以參考下2015-07-07
利用Python實(shí)現(xiàn)K-Means聚類的方法實(shí)例(案例:用戶分類)
k-means是發(fā)現(xiàn)給定數(shù)據(jù)集的k個(gè)簇的算法,也就是將數(shù)據(jù)集聚合為k類的算法,下面這篇文章主要給大家介紹了關(guān)于利用Python實(shí)現(xiàn)K-Means聚類的相關(guān)資料,需要的朋友可以參考下2022-05-05
詳解python如何通過(guò)numpy數(shù)組處理圖像
Numpy?是?Python?中科學(xué)計(jì)算的核心庫(kù),NumPy?這個(gè)詞來(lái)源于?Numerical?和?Python?兩個(gè)單詞。它提供了一個(gè)高性能的多維數(shù)組對(duì)象,以及大量的庫(kù)函數(shù)和操作,可以幫助程序員輕松地進(jìn)行數(shù)值計(jì)算,廣泛應(yīng)用于機(jī)器學(xué)習(xí)模型、圖像處理和計(jì)算機(jī)圖形學(xué)、數(shù)學(xué)任務(wù)等領(lǐng)域2022-03-03
OpenCV哈里斯角檢測(cè)|Harris?Corner理論實(shí)踐
這篇文章主要為大家介紹了OpenCV哈里斯角檢測(cè)|Harris?Corner理論實(shí)踐,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python實(shí)現(xiàn)引用其他路徑包里面的模塊
這篇文章主要介紹了python實(shí)現(xiàn)引用其他路徑包里面的模塊,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03
Python進(jìn)程間通信Queue實(shí)例解析
這篇文章主要介紹了Python進(jìn)程間通信Queue實(shí)例解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Pytorch 如何查看、釋放已關(guān)閉程序占用的GPU資源
這篇文章主要介紹了Pytorch 查看、釋放已關(guān)閉程序占用的GPU資源的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2021-05-05
對(duì)python中的six.moves模塊的下載函數(shù)urlretrieve詳解
今天小編就為大家分享一篇對(duì)python中的six.moves模塊的下載函數(shù)urlretrieve詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12

