I'm trying to create a Python script that can do two things:
- Run normally if no args are present.
- If
install
is passed as argument, install itself to a specific directory (/tmp
), and run the installed version in the background, detached from the current process.
I've tried multiple combinations of subprocess.run
, subprocess.Popen
with the shell
, close_fds
and other options (even tried nohup
), but since I do not have a good understanding of how process spawning works, I do not seem to be using the correct one.
What I'm looking for when I use the install
argument is to see "Installing..." and that's it, the new process should be running in the background detached and my shell ready. But what I see is the child process still attached and my terminal busy outputting "Running..." just after the installing message.
How should this be done?
import subprocess
import sys
import time
import os
def installAndRun():
print('Installing...')
scriptPath = os.path.realpath(__file__)
scriptName = (__file__.split('/')[-1] if '/' in __file__ else __file__)
# Copy script to new location (installation)
subprocess.run(['cp', scriptPath, '/tmp'])
# Now run the installed script
subprocess.run(['python3', f'/tmp/{scriptName}'])
def run():
for _ in range(5):
print('Running...')
time.sleep(1)
if __name__=="__main__":
if 'install' in sys.argv:
installAndRun()
else:
run()
Edit: I've just realised that the process does not end when called like that.