1

誰能告訴我爲什麼下面的代碼給出錯誤「無法啓動一個進程兩次」?根據我的估算,p1和p2應該已經被p.terminate()命令強制關閉了。編輯:在一些更多的代碼中添加了上下文 - 想要拿出一個簡單的例子,但忽略了while循環Python多處理 - 進程終止(不能啓動一個進程兩次)

import time 
import os 
from multiprocessing import Process 
import datetime 

def a(): 
    print ("a starting") 
    time.sleep(30) 
    print ("a ending") 

def b(): 
    print ("b starting") 
    time.sleep(30) 
    print ("b ending") 

morning = list(range(7,10)) 
lunch = list(range(11,14)) 
evening = list(range(17,21)) 
active = morning + lunch + evening 

if __name__=='__main__': 
    p1 = Process(target = a) 
    p2 = Process(target = b) 
    while True: 
     while (datetime.datetime.now().time().hour) in active: 
      p1.start() 
      p2.start() 
      time.sleep(5) 
      p1.terminate() 
      p2.terminate() 
      time.sleep(5) 
     else: 
      print ("Outside hours, waiting 30 mins before retry") 
      time.sleep(1800) 
+0

爲什麼兩個'p1.start()'和'p2.start()'? – Arman

+0

哦,對不起!有一個while循環封裝這個在一天中的某個時間反覆運行代碼 –

回答

2

它說你不能啓動一個進程兩次。這正是您在終止後再次撥打p1.start()p2.start()時所要做的。嘗試像開始時一樣重新創建它們。

p1.terminate() 
p2.terminate() 
time.sleep(5) 
p1 = Process(target = a) 
p2 = Process(target = b) 
p1.start() 
p2.start() 
+0

啊!我沒有意識到你必須不斷重新定義流程。我將錯誤「你不能重新啓動一個進程」解釋爲「你不能重新運行已經運行的進程」,所以認爲terminate()有錯誤。雖然我不得不反覆重新定義流程,但似乎並不合乎邏輯 –