user1561753
user1561753

Reputation: 357

Threading behavior is weird in python subprocess

So I essentially have a case like this where in my main script I have

command = 'blender -b ' + settings.BLENDER_ROOT + 'uploadedFileCheck.blend -P ' + settings.BLENDER_ROOT + 'uploadedFileCheck.py -noaudio'
process = Popen(command.split(' ') ,stdout=PIPE, stderr=PIPE)
out, err = process.communicate()

And in the subprocess script uploadedFileCheck.py I have the line

exportFile(fileIn, fileOut)
Thread(target=myfunction).start()

So I expect the subprocess to be finished, or at least to return to out, err after the exportFile() call, but it seems it's waiting for the Thread to finish as well. Does anyone understand this behavior?

Also, in case you're wondering, I'm calling that other python file as a subprocess because the main script is in python2 and that script (blender) is in python3, but that's irrelevant (and can't change)

Upvotes: 1

Views: 504

Answers (1)

dano
dano

Reputation: 94901

A process won't exit until all its non-daemon threads have exited. By default, Thread objects in Python are created as non-daemon threads. If you want your script to exit as soon as the main thread is done, rather than waiting for the spawned thread to finish, set the daemon flag on the Thread object to True prior to starting it:

t = Thread(target=myfunction)
t.daemon = True
t.start()

Note that this will kill the daemon thread in a non-graceful way, without any cleanup occuring. If you're doing any kind of work in that thread that needs to be cleaned up, you should consider an approach where you signal the thread to shut itself down, instead.

Upvotes: 2

Related Questions