2016-09-19 14 views
1

我需要打開目標在不同文件中定義的線程。如何打開目標位於另一個文件中的線程?

我想通過一個字符串傳遞目標名稱,當然包含我想要在線程上運行的函數的名稱。 這是不可能的,或者我錯過了什麼?

舉例來說,這裏是我的代碼:

這裏是有目標函數的代碼:

# command.py 

def hello(): 
    print("hello world") 

,這裏是我的代碼將運行:

# run.py 

import threading 
import commands 

funcname = "hello" 

thread1 = threading.Thread(target= ... , daemon=True) 
thread1.start() 

什麼我需要把它作爲目標嗎?

回答

0

python docstarget必須是可調用的對象。從你的例子中,你應該能夠只是把

target=command.hello

+0

呀,但我怎麼從字符串funcname的「提取物」可調用對象的招呼? – Mnovdef

+0

[在StackOverflow中查看此問題](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python ) 你可以像'getattr(commands,funcname)()' – Dillanm

+0

或像'thread1 = threading.Thread(target = getattr(commands,funcname),...)那樣做' – Dillanm

相關問題