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利用WMI实现ping命令的例子

WMI是Windows系统的一大利器,Python的win32api库提供了对WMI的支持,安装win32api即可使用 WMI。 本例通过WMI的WQL实现ping命令。 impo...

基于python的多进程共享变量正确打开方式

多进程共享变量和获得结果 由于工程需求,要使用多线程来跑一个程序。但是因为听说python的多线程是假的,于是使用多进程,反正任务需要共享的参数少。 查阅资料,发现实现多进程主要使用Mu...

Falsk 与 Django 过滤器的使用与区别详解

1,flask中内置的过滤器模板中常用方法: {#过滤器调用方式{{变量|过滤器名称}} #} <!-- safe过滤器,可以禁用转义 --> {{'<st...

Python中将字典转换为XML以及相关的命名空间解析

尽管 xml.etree.ElementTree 库通常用来做解析工作,其实它也可以创建XML文档。 例如,考虑如下这个函数: from xml.etree.ElementTree...

用Python的Django框架编写从Google Adsense中获得报表的应用

 我完成了更新我们在 Neutron的实时收入统计。在我花了一周的时间完成并且更新了我们的PHP脚本之后,我最终认决定开始使用Python进行抓取,这是值得我去花费我的时间和精...