欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中subprocess模塊用法實(shí)例詳解

 更新時(shí)間:2015年05月20日 14:35:01   作者:網(wǎng)海水手  
這篇文章主要介紹了Python中subprocess模塊用法,實(shí)例分析了subprocess模塊的相關(guān)使用技巧,需要的朋友可以參考下

本文實(shí)例講述了Python中subprocess模塊用法。分享給大家供大家參考。具體如下:

執(zhí)行命令:

>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1

測(cè)試調(diào)用系統(tǒng)中cmd命令,顯示命令執(zhí)行的結(jié)果:

x=subprocess.check_output(["echo", "Hello World!"],shell=True)
print(x)
"Hello World!"

測(cè)試在python中顯示文件內(nèi)容:

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)

查看網(wǎng)絡(luò)設(shè)置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]) #打印網(wǎng)絡(luò)信息
Windows IP Configuration
    Host Name . . . . .

我們可以在Popen()建立子進(jìn)程的時(shí)候改變標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤,并可以利用subprocess.PIPE將多個(gè)子進(jìn)程的輸入和輸出連接在一起,構(gòu)成管道(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();因?yàn)閏ommunicate通信一次之后即關(guān)閉了管道.這時(shí)可以試試下面的方法:

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

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論