2017-07-19 43 views
0

我有這樣的例子代碼:的Python - 線程 - 同時執行

# some imports that I'm not including in the question 

class daemon: 
    def start(self): 
     # do something, I'm not including what this script does to not write useless code to the question 
     self.run() 

    def run(self): 
     """You should override this method when you subclass Daemon. 

     It will be called after the process has been daemonized by 
     start() or restart(). 
     """ 

class MyDaemon(daemon): 
    def run(self): 
     while True: 
      time.sleep(1) 

if __name__ == "__main__": 
    daemonz = MyDaemon('/tmp/daemon-example.pid') 
    daemonz.start() 

def firstfunction(): 
    # do something 
    secondfunction() 

def secondfunction(): 
    # do something 
    thirdfunction() 

def thirdfunction(): 
    # do something 

# here are some variables set that I am not writing 
firstfunction() 

如何從類「守護」的運行(個體經營)函數退出並執行了firstFunction會()一樣寫在最後一行?我是一個Python的新手,我試圖學習

#編輯 我設法將守護程序類實現到treading類。但是我首先處於相同的情況,腳本停留在守護進程類中,不執行其他行。

class MyThread(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 

    def daemonize(self): 
    # istructions to daemonize my script process 

    def run(self): 
     self.daemonize() 


def my_function(): 
    print("MyFunction executed") # never executed 

thread = MyThread() 
thread.start() 
my_function() # the process is successfully damonized but 
       # this function is never executed 
+2

您的代碼將卡在MyDaemon中的while循環中嗎?這就是爲什麼你的代碼永遠不會到達firstfunction()。 –

+0

'run()'方法中的'while True'條件將永遠保持您的程序在循環中。你打算有其他的條件嗎? – Sanjay

+0

實際上,我必須在類「守護進程」的def run(self)中編寫下一個指令,但此刻我沒有寫任何內容,因爲我問了我可以做什麼來傳遞給其他類的命令,如最後一行「firstfunction()」。我能怎麼做? – AllExJ

回答

1

您可以使用關鍵字break退出循環,並繼續到下一行。 return可用於退出功能。

class daemon: 
    def start(self): 
     self.run() 

    def run(self): 
     while True: 
      break 
     return 
     print() # This never executes 

如果你想MyDaemon並肩你的代碼的其餘部分運行,你必須使它進程或線程。然後代碼自動繼續到下一行,而MyDaemon類(線程/進程)運行。

import threading 


class MyThread(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 

    def run(self): 
     print("Thread started") 
     while True: 
      pass 


def my_function(): 
    print("MyFunction executed") 

thread = MyThread() 
thread.start()  # executes run(self) 
my_function() 

此代碼將產生以下結果:

Thread started 
MyFunction executed 

爲了thread一個守護進程,你可以使用thread.setDaemon(True)。該功能必須在線程啓動之前調用:

thread = MyThread() 
thread.setDaemon(True) 
thread.start() 
my_function() 
+0

和守護進程將繼續工作? – AllExJ

+0

@AllExJ不太確定。很長一段時間,因爲我用Python編程。如果我是對的,你需要多線程或多處理。如果程序執行時該進程將退出,則不需要守護進程。當啓動一個進程時,代碼在進程運行時繼續到下一行。我將查找多線程,並在此創建一個示例。 :) – Andreas

+0

非常感謝!所以在函數「my_function」中,我必須將代碼轉換爲守護進程的權利? – AllExJ