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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章