Search code examples
pythonsubprocesspopen

Run one subprocess after another in a single call that works in the background


To run a subprocess in the background without disturbing the continuity of the main code I call the Python file like this:

Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

Is there any way I can use this call to run that first file('secondary.py') and then run another file ('tertiary.py') when it finishes the process?

Something like for example:

Popen(['secondary.py','tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

Note:

I can't call one below the other like this:

Popen(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
Popen(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)

Because they would become two separate subprocesses, which is not my expected goal, I need to finish one and then run the other.


Solution

  • subprocess.run waits until the command is complete. You could create a background thread that runs all the commands you want in a row.

    import threading
    import subprocess
    
    def run_background():
        subprocess.run(['secondary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
        subprocess.run(['tertiary.py'], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True)
    
    bg_thread = threading.Thread(target=run_background)
    bg_thread.start()
    

    Because this was not marked as a daemon thread, the main thread will wait until this thread has completed while exiting the program.