Python中subprocess模組用法執行個體詳解
本文執行個體講述了Python中subprocess模組用法。分享給大家供大家參考。具體如下:
執行命令:
?
|
1
2
3
4 |
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
|
測試調用系統中cmd命令,顯示命令執行的結果:
?
|
1
2
3 |
x=subprocess.check_output(["echo", "Hello World!"],shell=True)
print(x)
"Hello World!"
|
測試在python中顯示檔案內容:
?
|
1
2
3
4
5 |
y=subprocess.check_output(["type", "app2.cpp"],shell=True)
print(y)
#include <iostream>
using namespace std;
......
|
查看ipconfig -all命令的輸出,並將將輸出儲存到檔案tmp.log中:
?
|
1
2 |
handle = open(r'd:\tmp.log','wt')
subprocess.Popen(['ipconfig','-all'], stdout=handle)
|
查看網路設定ipconfig -all,儲存到變數中:
?
|
1
2
3
4
5
6 |
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):
?
|
1
2
3
4
5 |
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通訊一次之後即關閉了管道.這時可以試試下面的方法:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
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程式設計有所協助。