2011-06-29 65 views
0

我正在尋找一個新的線程在另一個python腳本中調用python函數。 我有經驗使用subprocess.Popen,但我用它在命令行調用.exe的。任何人推薦如何做到這一點或模塊使用?Python多線程幫助

def main(argv): 
    call otherdef(1,2,3) in a new thread 
    sleep for 10 minutes 
    kill the otherdef process 

def otherdef(num1, num2, num3): 
    while(True): 
     print num1 
+1

你說'在一個新的線程'你的意思是'在一個新的過程' – Nix

+0

而不是殺死它,爲什麼你沒有過程中止10分鐘後過去? – Nix

回答

3

這是一個解決方案,但它不完全像你問,因爲它很複雜,殺死一個線程。它更好地讓線程自行終止,所有線程默認爲守護進程= False(除非它的父線程是守護進程),所以當主線程死亡時,線程將活着。將它設置爲true,它將隨着主線程而死。

基本上你所做的只是啓動一個Thread並給它一個運行方法。您需要能夠傳遞參數,因爲您可以看到我傳遞了一個參數args=以傳遞給目標方法的值。

import time 
import threading 


def otherdef(num1, num2, num3): 
    #Inside of otherdef we use an event to loop on, 
    #we do this so we can have a convent way to stop the process. 

    stopped = threading.Event() 
    #set a timer, after 10 seconds.. kill this loop 
    threading.Timer(10, stopped.set).start() 
    #while the event has not been triggered, do something useless 
    while(not stopped.is_set()): 
     print 'doing ', num1, num2, num3 
     stopped.wait(1) 

    print 'otherdef exiting' 

print 'Running' 
#create a thread, when I call start call the target and pass args 
p = threading.Thread(target=otherdef, args=(1,2,3)) 
p.start() 
#wait for the threadto finish 
p.join(11) 

print 'Done'  

它仍不清楚,如果你想有一個進程或線程,但如果你想有一個Process進口多,並切換到threading.Thread(multiprocessing.Process(,一切保持不變。

+0

「所有線程默認爲守護進程」 - 你確定嗎? – senderle