python进程类subprocess的一些操作方法例子
作者:junjie 时间:2021-08-26 16:21:35
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()
while(curline != ""):
print (curline)
curline = p.stdout.readline()
p.wait()
print (p.returncode)
6) call函数可以认为是对popen和wait的分装,直接对call函数传入要执行的命令行,将命令行的退出code返回。
def TestCall():
retcode = subprocess.call("c:\\test.bat")
print (retcode)
7)subprocess.getoutput 和 subprocess.getstatusoutput ,基本上等价于subprocess.call函数,但是可以返回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的参数,第一个为字符串(或者也可以为多个非命名的参数),表示你要执行的命令和命令的参数;后面的均为命名参数;shell=True,表示你前面的传入的命令将在shell下执行,如果你的命令是个可执行文件或bat,不需要指定此参数;stdout=subprocess.PIPE用来将新进程的输出重定向,stderr=subprocess.STDOUT将新进程的错误输出重定向到stdout,stdin=subprocess.PIPE用来将新进程的输入重定向;universal_newlines=True表示以text的方式打开stdout和stderr。
其他的不推荐使用的模块:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python自动化测试selenium核心技术等待条件教程
![](https://img.aspxhome.com/file/2023/2/103792_0s.jpg)
百分百成功的全网最简约sklearn环境配置教程
![](https://img.aspxhome.com/file/2023/5/101735_0s.png)
使用Post提交时须将空格转换成加号的解释
python和pygame实现简单俄罗斯方块游戏
![](https://img.aspxhome.com/file/2023/2/69532_0s.gif)
Python unittest装饰器实现原理及代码
python爬取之json、pickle与shelve库的深入讲解
Python实现获取照片拍摄日期并重命名的方法
![](https://img.aspxhome.com/file/2023/4/100864_0s.jpg)
Django查询优化及ajax编码格式原理解析
python for循环赋值问题
教你用python从日期中获取年、月、日和星期等30种信息
![](https://img.aspxhome.com/file/2023/1/102861_0s.png)
教你轻松掌握如何正确的修复Access数据库
Python使用Redis实现作业调度系统(超简单)
AJAX和DOM的运行经验
Python之re模块详解
python 遍历目录(包括子目录)下所有文件的实例
Sql server 2005安装时ASP.Net版本注册要求警告的解决方法
![](https://img.aspxhome.com/file/2023/7/78067_0s.png)
python闭包、深浅拷贝、垃圾回收、with语句知识点汇总
![](https://img.aspxhome.com/file/2023/9/81739_0s.png)
mysql之innodb的锁分类介绍
Django ORM F对象和Q对象查询
![](https://img.aspxhome.com/file/2023/5/133845_0s.png)