[英]Forking a process in python
我已經更新了問題,以便更清楚地顯示我要在后台打印數字並檢查條件時執行功能。
import time
number = [1,100]
t0 = time.time()
for i in number:
print i
t1= time.time()
def sum_two_numbers():
t2 = time.time()
c=1+2
t3 =time.time()
verify t0<t2 and t3<<t1
由於這兩個腳本是完全獨立的,因此只需使用subprocess.Popen()
:
import subprocess
script1 = subprocess.Popen(['/path/to/script1', 'arg1', 'arg2', 'etc'])
script2 = subprocess.Popen(['/path/to/script2', 'arg1', 'arg2', 'etc'])
就是這樣,兩個腳本都在后台運行1 。 如果要等待它們之一完成,請根據需要調用script1.wait()
或script2.wait()
。 例:
import subprocess
script1 = subprocess.Popen(['sleep', '30'])
script2 = subprocess.Popen(['ls', '-l'])
script1.wait()
您會發現腳本2將產生其輸出並在腳本1之前終止。
如果您需要捕獲任何一個子進程的輸出,則將需要使用管道,然后事情會變得更加復雜。
1 這里的“背景”與通常在shell中運行的后台進程的* nix概念不同; 例如,沒有工作控制。 WRT subprocess
進程,只是創建了一個新的子進程並加載了所請求的可執行文件。 根據默認的Popen()
選項,如果shell=False
, Popen()
涉及任何shell。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.