python进程类subprocess的一些操作方法例子
subprocess.Popen用来创建子进程。
1)Popen启动新的进程与父进程并行执行,默认父进程不等待新进程结束。
defTestPopen():
importsubprocess
p=subprocess.Popen("dir",shell=True)
foriinrange(250):
print("otherthings")
2)p.wait函数使得父进程等待新创建的进程运行结束,然后再继续父进程的其他任务。且此时可以在p.returncode中得到新进程的返回值。
defTestWait():
importsubprocess
importdatetime
print(datetime.datetime.now())
p=subprocess.Popen("sleep10",shell=True)
p.wait()
print(p.returncode)
print(datetime.datetime.now())
3)p.poll函数可以用来检测新创建的进程是否结束。
defTestPoll():
importsubprocess
importdatetime
importtime
print(datetime.datetime.now())
p=subprocess.Popen("sleep10",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。
defTestKillAndTerminate():
p=subprocess.Popen("notepad.exe")
t=1
while(t<=5):
time.sleep(1)
t+=1
p.kill()
#p.terminate()
print("newprocesswaskilled")
5)p.communicate可以与新进程交互,但是必须要在popen构造时候将管道重定向。
defTestCommunicate():
importsubprocess
cmd="dir"
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
(stdoutdata,stderrdata)=p.communicate()
ifp.returncode!=0:
print(cmd+"error!")
#defaultlythereturnstdoutdataisbytes,needconverttostrandutf8
forrinstr(stdoutdata,encoding='utf8').split("\n"):
print(r)
print(p.returncode)
defTestCommunicate2(): importsubprocess cmd="dir" #universal_newlines=True,itmeansbytextwaytoopenstdoutandstderr 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)