2016-08-13 114 views
-1

我有一個for循環,在循環內我檢查與if東西,並且當條件滿足時,我啓動一個函數。這個功能包括一個等待期(time.sleep),我注意到循環暫停,直到該功能完成。一個函數,不會停止/暫停我的腳本

有沒有什麼辦法讓我的循環在執行函數時保持運行? 我想也許啓動另一個腳本,但我甚至不知道這也不會暫停循環...

目標是能夠在第一個完成之前再次啓動該功能。

壽代碼一種看起來像這樣

def myfunction(): 
    time.sleep(30) 
    print("waited 30 seconds...") 
    do something 
for something 
    if condition: 
     myfunction() 
    print("the loop is resumed...") 
+3

後的實際代碼而不是它的描述。聽起來你想[多處理](https://docs.python.org/3.5/library/multiprocessing.html)。 – Holloway

+0

該代碼是祕密的,對不起 – Seb

+1

這很好,我們不希望整個事情;創建一個匿名[mcve]。 – jonrsharpe

回答

0

您所描述的問題可以很平凡簡單的線程解決像這樣:

import time 
import threading 

def myfunction(): 
    time.sleep(30) 
    print("waited 30 seconds.") 
    # do whatever else 

num = 0 
mythreads = [] 
while(True): # Just loop forever for demo purposes 
    num += 1 
    if num % 5 == 0: # Execute the function once every 5 times 
     newthread = threading.Thread(target=myfunction) 
     mythreads.append(newthread) 
     newthread.start() 
    print("The loop is resumed.") 
+0

看起來不錯我會嘗試一下,看看。一旦函數執行完成,蠑螈線程是否會自動停止? – Seb

+0

看起來像現在這樣工作。非常感謝! – Seb

+0

@Seb如果它適合你,請接受答案。 – Feneric