Python中subprocess模組用法執行個體詳解

來源:互聯網
上載者:User

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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.