2

I need to open a thread whose target is defined in a different file.

I would like to pass the target name through a string containing, of course, the name of the function I want to run on thread. Is that impossible, or am I missing something?

For instance, here is my code:

Here is the code that has the target function:

# command.py

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

and here is the code I will run:

# run.py

import threading
import commands

funcname = "hello"

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

What do i need to put as target?

Mnovdef
  • 157
  • 2
  • 5

1 Answers1

0

From the python docs the target has to be a callable object. From your example you should be able to just put

target=command.hello

Dillanm
  • 876
  • 12
  • 28
  • Yeah, but how do I "extract" the callable object hello from the string funcname? – Mnovdef Sep 19 '16 at 11:46
  • 1
    [see this issue on StackOverflow](http://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python) You can do it like `getattr(commands, funcname)()` – Dillanm Sep 19 '16 at 13:25
  • or like `thread1 = threading.Thread(target=getattr(commands, funcname), ...)` – Dillanm Sep 19 '16 at 13:32