Python中subprocess模块用法实例详解

yipeiwu_com6年前Python基础

本文实例讲述了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中最大递归深度值的探讨

Python中最大递归深度值的探讨

Python对递归函数设置是有默认值。 可以通过下面命令来查看设置的默认值 >>> import sys >>> sys.getrecursion...

python3 selenium 切换窗口的几种方法小结

第一种方法: 使用场景: 打开多个窗口,需要定位到新打开的窗口 使用方法: # 获取打开的多个窗口句柄 windows = driver.window_handles # 切换到当前...

Python 模拟登陆的两种实现方法

Python 模拟登陆的两种实现方法 有时候我们的抓取项目时需要登陆到某个网站上,才能看见某些内容的,所以模拟登陆功能就必不可少了,散仙这次写的文章,主要有2个例子,一个是普通写法写的,...

利用Python进行数据可视化常见的9种方法!超实用!

利用Python进行数据可视化常见的9种方法!超实用!

前言 如同艺术家们用绘画让人们更贴切的感知世界,数据可视化也能让人们更直观的传递数据所要表达的信息。 我们今天就分享一下如何用 Python 简单便捷的完成数据可视化。 其实利用 Pyt...

浅谈Python里面小数点精度的控制

要求较小的精度 round()内置方法 这个是使用最多的,刚看了round()的使用解释,也不是很容易懂。round()不是简单的四舍五入的处理方式。 For the built-in...