subprocess.Popen() 常用方法
2024-08-29 02:11:05
p.stdout.read() :用于读取标准输出,会一次性读取所有内容,返回一个字符串
p.stdout.readline() :用于读取标准输出,一次只读取一行内容,返回一个字符串
p.stdout.readlines() :用于读取标准输出,一次性读取所有内容,返回一个列表,每一行是列表的一个元素
from subprocess import Popen, PIPE p = Popen('ls /data', stdout=PIPE, shell=True)
for line in p.stdout.readlines():
print(line),
[root@localhost ~]$ python 1.py
1.txt
2.txt
3.txt
p.wait() :等待子进程结束,并返回状态码。如下,如果没有加上 p.wait(),则 sleep 100 还没有执行完,就会执行 print('End'),如果加上就会等待 sleep 100 执行完
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True)
p.wait()
print('End')
p.pid :用于查看子进程的PID
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True)
print(p.pid)
[root@localhost ~]$ python 1.py
35327
[root@localhost ~]$ ps aux | grep 35327
root 35327 0.0 0.0 107904 612 pts/0 S 17:56 0:00 sleep 100
root 35329 0.0 0.0 112676 984 pts/0 S+ 17:57 0:00 grep --color=auto 35327
p.poll() :用于检查子进程(命令)是否已经执行结束,没结束返回None,结束后返回状态码
#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
from subprocess import Popen, PIPE p = Popen('sleep 3', stdout=PIPE, shell=True) while True:
if p.poll() == None:
print('程序执行中...')
time.sleep(1)
else:
print('程序执行完毕, 状态码为:%s' % p.poll())
break
[root@localhost ~]$ python 1.py
程序执行中...
程序执行中...
程序执行中...
程序执行完毕, 状态码为:0
p.returncode :用于返回命令执行完之后的状态码
#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
from subprocess import Popen, PIPE p = Popen('sleep 3', stdout=PIPE, shell=True) while True:
if p.poll() == None:
print('程序执行中...')
time.sleep(1)
else:
print('程序执行完毕, 状态码为:%s' % p.returncode)
break
[root@localhost ~]$ python 1.py
程序执行中...
程序执行中...
程序执行中...
程序执行完毕, 状态码为:0
p.kill() :用于杀死子进程
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True)
print(p.pid)
p.kill()
[root@localhost ~]$ python 1.py
35403
[root@localhost ~]$ ps aux | grep 35403 # 可以看到子进程已经不在了
root 35405 0.0 0.0 112676 980 pts/0 S+ 18:12 0:00 grep --color=auto 35403
p.terminate() :用于终止子进程,与 kill() 差不多
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True)
print(p.pid)
p.terminate()
[root@localhost ~]$ python 1.py
35403
[root@localhost ~]$ ps aux | grep 35403 # 可以看到子进程已经不在了
root 35405 0.0 0.0 112676 980 pts/0 S+ 18:12 0:00 grep --color=auto 35403
p.communicate() :该方法可用来与子进程进行交互,比如发送数据到stdin,结果会返回一个元组,这个元组包含stdout和stderr
from subprocess import Popen, PIPE p = Popen('cat', stdin=PIPE, stdout=PIPE, shell=True)
print p.communicate('hello world')
[root@localhost ~]$ python 1.py
('hello world', None)
最新文章
- Ubuntu 使用笔记
- Web.Config如何输入特殊字符
- 【云计算】K8S DaemonSet 每个node上都运行一个pod
- perl随记(1)
- phpstorm使用技巧
- 基于visual Studio2013解决C语言竞赛题之1047百马问题
- 微信支付错误两个问题的解决:curl出错,错误码:60
- css3瀑布流
- DNA序列对齐问题
- How Tomcat Works 读书笔记 八 载入器 上
- ENSP模拟华为USG6000
- 2018.09.29 Lua
- Luogu3527 POI2011 Meteors 整体二分、树状数组、差分
- matlab学习(2) sort、sortrows
- Hbuilder用ajax连接阿里服务器上的servlet以及注意事项
- source insight设置tab键为4个空格
- Opengl绘制我们的小屋(三)纹理绘制
- chrome plugins
- sun 证书问题解决
- mysql数据库修改字符编码问题