Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to fork multiple shell commands/processes in Python?

Tags:

python

shell

Most of the examples I've seen with os.fork and the subprocess/multiprocessing modules show how to fork a new instance of the calling python script or a chunk of python code. What would be the best way to spawn a set of arbitrary shell command concurrently?

I suppose, I could just use subprocess.call or one of the Popen commands and pipe the output to a file, which I believe will return immediately, at least to the caller. I know this is not that hard to do, I'm just trying to figure out the simplest, most Pythonic way to do it.

Thanks in advance

like image 544
mrmbd Avatar asked Sep 02 '25 16:09

mrmbd


1 Answers

All calls to subprocess.Popen return immediately to the caller. It's the calls to wait and communicate which block. So all you need to do is spin up a number of processes using subprocess.Popen (set stdin to /dev/null for safety), and then one by one call communicate until they're all complete.

Naturally I'm assuming you're just trying to start a bunch of unrelated (i.e. not piped together) commands.

like image 68
Chris Eberle Avatar answered Sep 04 '25 04:09

Chris Eberle