Python中subprocess模块的使用
2013-11-08 13:24
204 查看
执行命令:
测试调用系统中cmd命令,显示命令执行的结果:
测试在python中显示文件内容:
查看ipconfig -all命令的输出,并将将输出保存到文件tmp.log中:
查看网络设置ipconfig -all,保存到变量中:
我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):
如果想频繁地和子线程通信,那么不能使用communicate();因为communicate通信一次之后即关闭了管道.这时可以试试下面的方法:
>>> 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识别图片使用pytesser模块时__init__.py调用subprocess模块出现WindowsError: [Error 2]
- 使用python的subprocess模块遇到的问题及其解决
- python的subprocess模块使用方法
- Python中subprocess模块的使用
- 学习笔记--Python中subprocess模块的使用
- Python调用linux系统命令--使用subprocess模块
- 在python中执行外部可执行程序,使用subprocess模块
- Python中subprocess模块的使用
- Python的subprocess模块的使用
- Python之subprocess模块的使用
- python3 subprocess模块使用
- python 使用subprocess模块来执行shell命令
- 菜鸟学Python之Django配置Admin使用(一)
- Python re库match(),serach(),findall()和finditer()方法使用
- Python中Update()函数的使用
- 使用python实现快速搭建简易的FTP服务器
- python 文件处理模块使用,对一个文件追加写入
- 使用python编写批量ping主机脚本
- Python Paramiko模块的使用
- python Popen使用