Python中subprocess模块用法实例详解
作者:网海水手 时间:2021-05-30 20:43:12
本文实例讲述了Python中subprocess模块用法。分享给大家供大家参考。具体如下:
执行命令:
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
测试调用系统中cmd命令,显示命令执行的结果:
x=subprocess.check_output(["echo", "Hello World!"],shell=True)
print(x)
"Hello World!"
测试在python中显示文件内容:
y=subprocess.check_output(["type", "app2.cpp"],shell=True)
print(y)
#include <iostream>
using namespace std;
......
查看ipconfig -all命令的输出,并将将输出保存到文件tmp.log中:
handle = open(r'd:\tmp.log','wt')
subprocess.Popen(['ipconfig','-all'], stdout=handle)
查看网络设置ipconfig -all,保存到变量中:
output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)
oc=output.communicate()#取出output中的字符串
#communicate() returns a tuple (stdoutdata, stderrdata).
print(oc[0]) #打印网络信息
Windows IP Configuration
Host Name . . . . .
我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):
child1 = subprocess.Popen(["dir","/w"], stdout=subprocess.PIPE,shell=True)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE,shell=True)
out = child2.communicate()
print(out)
(' 9 24 298\n', None)
如果想频繁地和子线程通信,那么不能使用communicate();因为communicate通信一次之后即关闭了管道.这时可以试试下面的方法:
p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
p.stdin.write('your command')
p.stdin.flush()
#......do something
try:
#......do something
p.stdout.readline()
#......do something
except:
print('IOError')
#......do something more
p.stdin.write('your other command')
p.stdin.flush()
#......do something more
希望本文所述对大家的Python程序设计有所帮助。
标签:Python,subprocess
0
投稿
猜你喜欢
python生成九宫格图片
2022-09-09 04:46:34
Element-ui DatePicker显示周数的方法示例
2024-05-29 22:45:19
Python Log文件大小设置及备份的方法
2022-08-02 13:46:14
python实现数值积分的Simpson方法实例分析
2023-08-01 17:35:01
centos 7安装mysql5.5的方法
2024-01-22 01:29:32
Django数据库迁移常见使用方法
2024-01-17 09:57:26
Python基础知识学习之类的继承
2022-09-02 15:41:05
python实现挑选出来100以内的质数
2023-03-03 16:32:04
Pytorch 之修改Tensor部分值方式
2023-04-11 06:45:12
sql server数据库最大Id冲突问题解决方法之一
2012-01-05 19:28:42
详解python中xlrd包的安装与处理Excel表格
2021-10-23 06:06:59
tensorflow 使用flags定义命令行参数的方法
2021-03-20 10:43:23
sql存储过程获取汉字拼音头字母函数
2011-11-03 16:58:05
解决Golang中goroutine执行速度的问题
2023-08-25 20:12:12
Centos7.3下mysql5.7.18安装并修改初始密码的方法
2024-01-20 00:02:11
Python数据可视化之使用matplotlib绘制简单图表
2022-08-27 19:27:53
laravel执行php artisan migrate报错的解决方法
2024-06-05 09:44:39
求任意自然数内的素数
2009-10-15 12:21:00
sql自动增长标识导致导入数据问题的解决方法
2023-07-04 04:39:22
MySQL 出现错误1418 的原因分析及解决方法
2024-01-27 12:06:34