本文实例讲述了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 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 somethingtry: #......do something p.stdout.readline() #......do somethingexcept: print('ioerror')#......do something morep.stdin.write('your other command')p.stdin.flush()#......do something more
希望本文所述对大家的python程序设计有所帮助。