HenryHunt HenryHunt - 2 months ago 8x
Python Question

Running lines of code inside code for new thread instead of specifying a target function to run

I've tried a lot of searching but didn't really know how to word my problem, so it may be that there's a solution that I couldn't find because I didn't know how to search for it.

I have a single line of code that I'd like to run in a separate thread. So far I have the impression that to create a new thread you have to put the code you want to run inside its own function and then call that function using the

argument when starting the thread:

threading.Thread(target = functionName).start()

This is fine and I have it working like this, however because I'm only running a single line of code it seems a bit pointless to have it in its own function, and I'd like to get rid of this. I want to create the thread and effectively specify the actual line of code itself as the
instead of the function name.

I can do this in C#:

new Thread(delegate()
// any amount of code goes here and it will be run in its own thread

But is there any way I can do this in Python?


Using python you can make inline functions using lambda

threading.Thread(target = lambda: print('hi')).start()

In this case, note that 'hi' won't show in the terminal as it's in another thread