Search code examples
pythonlinuxsubprocessgnu-screen

Python - How to launch a subprocess before exiting the program (which is running on a detached screen)?


For some reason, I would like to launch a script just before exiting my current one. I found one simple way to do it:

script1.py:

#**
#some code
#**
p=subprocess.Popen(["python", "script2.py"])

With this, if I run script1, it will launch script2 at the end just before exiting.

However if I run script1 within a screen (screen python script1.py), the screen will terminate before script2 has even a chance to start.

Moreover, since script2 is very long, I would like not to wait that it ends before exiting script1. Is there a way to do it? Maybe by launching script2 in another screen? If so how can I do this?


Solution

  • You can create the second script and then wait for it to complete

    p=subprocess.Popen(["python", "script2.py"])
    p.wait()
    

    or more elegantly you can use os.execv that will replace your python interpreter by the new one (the PID will stay unchanged, you'll keep the console).

    os.execv("/usr/bin/python", ["/usr/bin/python", "script2.py"])