1. 程式人生 > >Python的線程&進程&協程[2] -> 進程 -> 多進程的基本使用

Python的線程&進程&協程[2] -> 進程 -> 多進程的基本使用

程序 參數 .html shell 測試 求一個 輸入 cti hello

多進程的基本使用


1 subprocess 常用函數示例

首先定義一個子進程調用的程序,用於打印一個輸出語句,並獲取命令行參數

1 import sys
2 print(Called_Function.py called, Hello world.)
3 try:
4     print(Got para, sys.argv[1:])
5 except:
6     pass

再定義主函數,即父進程,分別測試 run() / call() / check_call() / getstatusoutput() / getoutput() / ckeck_output函數。

 1 import
subprocess 2 3 # subprocess.run() 4 print(---------subprocess.run------------) 5 re = subprocess.run([python, Called_Function.py, para_1, para_2]) 6 print(subprocess.run() test returns obj:, re) 7 print(Return code is: {0}, stdout is: {1}, stderr is: {2}.format(re.returncode, re.stdout, re.stderr))
8 9 # subprocess.call() 10 print(\n---------subprocess.call------------) 11 print(subprocess.call() test returns code:, subprocess.call([python, Called_Function.py, para_1, para_2])) 12 13 # subprocess.ckeck_call() 14 print(\n---------subprocess.check_call------------) 15 try: 16 print
(subprocess.check_call() test returns code:, subprocess.check_call([python, Called_Function.py])) 17 except subprocess.CalledProcessError: 18 print(Failed to call.) 19 20 # subprocess.getstatusoutput() 21 print(\n---------subprocess.getstatusoutput------------) 22 print(subprocess.getstatusoutput() test returns:, subprocess.getstatusoutput([python, Called_Function.py])) 23 24 # subprocess.getoutput() 25 print(\n---------subprocess.getstatusoutput------------) 26 print(subprocess.getoutput() test returns:, subprocess.getoutput([python, Called_Function.py])) 27 28 # subprocess.check_output() 29 print(\n---------subprocess.check_output------------) 30 print(subprocess.check_output() test returns:, subprocess.check_output([python, Called_Function.py]))

2 利用Popen類與子進程交互

首先定義一個子進程調用的函數,函數中需求一個輸入

1 x = input(Please input something.)
2 print(x, Hello World!)
3 # Raise an error
4 print(y)

再定義父進程的函數

 1 import subprocess
 2 
 3 prcs = subprocess.Popen([python, Called_Function_Popen.py],
 4                         stdout=subprocess.PIPE,
 5                         stdin=subprocess.PIPE,
 6                         stderr=subprocess.PIPE,
 7                         universal_newlines=True,
 8                         shell=True)
 9 
10 print(subprocess pid:, prcs.pid)
11 
12 re = prcs.communicate(These string are from stdin)
13 print(\nSTDOUT:, re[0])
14 print(\nSTDERR:, re[1])
15 if prcs.poll():
16     print(\nThe subprocess has been done)


相關閱讀


1. subprocess 模塊

Python的線程&進程&協程[2] -> 進程 -> 多進程的基本使用