2016-09-19 1 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() 

何私は目標として置く必要がありますか? python docstargetから

答えて

0

は呼び出し可能オブジェクトである必要があります。あなたの例から、あなただけのうん

target=command.hello

+0

を置くことができるはずですが、どのように私は、文字列関数funcnameからこんにちは呼び出し可能オブジェクトを「抽出」しますか? – Mnovdef

+0

http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python([StackOverflowの上でこの問題を参照してください] ) 'getattr(commands、funcname)()' – Dillanm

+0

や 'thread1 = threading.Thread(target = getattr(commands、funcname)...) 'のようにすることができます。 – Dillanm

関連する問題