subprocess.Popen用來創建子進程。
1)Popen啟動新的進程與父進程并行執行,默認父進程不等待新進程結束。
代碼如下:
def TestPopen():
import subprocess
p=subprocess.Popen("dir",shell=True)
for i in range(250) :
print ("other things")
2)p.wait函數使得父進程等待新創建的進程運行結束,然后再繼續父進程的其他任務。且此時可以在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函數可以用來檢測新創建的進程是否結束。
代碼如下:
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用來結束創建的新進程,在windows系統上相當于調用TerminateProcess(),在posix系統上相當于發送信號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構造時候將管道重定向。
代碼如下:
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()
新聞熱點
疑難解答