python進程類subprocess的一些操作方法例子
subprocess.Popen用來創(chuàng)建子進程。
1)Popen啟動新的進程與父進程并行執(zhí)行,默認父進程不等待新進程結束。
def TestPopen():
import subprocess
p=subprocess.Popen("dir",shell=True)
for i in range(250) :
print ("other things")
2)p.wait函數(shù)使得父進程等待新創(chuàng)建的進程運行結束,然后再繼續(xù)父進程的其他任務。且此時可以在p.returncode中得到新進程的返回值。
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ù)可以用來檢測新創(chuàng)建的進程是否結束。
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用來結束創(chuàng)建的新進程,在windows系統(tǒng)上相當于調(diào)用TerminateProcess(),在posix系統(tǒng)上相當于發(fā)送信號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可以與新進程交互,但是必須要在popen構造時候?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ù)可以認為是對popen和wait的分裝,直接對call函數(shù)傳入要執(zhí)行的命令行,將命令行的退出code返回。
def TestCall():
retcode = subprocess.call("c:\\test.bat")
print (retcode)
7)subprocess.getoutput 和 subprocess.getstatusoutput ,基本上等價于subprocess.call函數(shù),但是可以返回output,或者同時返回退出code和output。
但是可惜的是好像不能在windows平臺使用,在windows上有如下錯誤:'{' 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)總結
popen的參數(shù),第一個為字符串(或者也可以為多個非命名的參數(shù)),表示你要執(zhí)行的命令和命令的參數(shù);后面的均為命名參數(shù);shell=True,表示你前面的傳入的命令將在shell下執(zhí)行,如果你的命令是個可執(zhí)行文件或bat,不需要指定此參數(shù);stdout=subprocess.PIPE用來將新進程的輸出重定向,stderr=subprocess.STDOUT將新進程的錯誤輸出重定向到stdout,stdin=subprocess.PIPE用來將新進程的輸入重定向;universal_newlines=True表示以text的方式打開stdout和stderr。
其他的不推薦使用的模塊:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
相關文章
Tensorflow實現(xiàn)在訓練好的模型上進行測試
今天小編就為大家分享一篇Tensorflow實現(xiàn)在訓練好的模型上進行測試,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
Python通過調(diào)用有道翻譯api實現(xiàn)翻譯功能示例
這篇文章主要介紹了Python通過調(diào)用有道翻譯api實現(xiàn)翻譯功能,結合實例形式分析了基于Python實現(xiàn)的有道翻譯api調(diào)用相關操作技巧,需要的朋友可以參考下2018-07-07
動態(tài)規(guī)劃之矩陣連乘問題Python實現(xiàn)方法
這篇文章主要介紹了動態(tài)規(guī)劃之矩陣連乘問題Python實現(xiàn)方法,較為詳細的分析了矩陣連乘問題的概念、原理并結合實例形式分析了Python相關實現(xiàn)技巧,需要的朋友可以參考下2017-11-11

