Search code examples
pythonunixsubprocessnohup

Have python script run in background of unix


I have a python script that I want to execute in the background on my unix server. The catch is that I need the python script to wait for the previous step to finish before moving onto the next task, yet I want my job to continue to run after I exit.

I think I can set up as follows but would like confirmation:

An excerpt of the script looks like this where command 2 is dependent on the output from command 1 since it outputs an edited executable file in same directory. I would like to point out that commands 1 and 2 do not have the nohup/& included.

subprocess.call('unix command 1 with options', shell=True)
subprocess.call('unix command 2 with options', shell=True)

If when I initiate my python script like so:

% nohup python python_script.py &

Will my script run in the background since I explicitly did not put nohup/& in my scripted unix commands but instead ran the python script in the background?


Solution

  • yes, by running your python script with nohup (no hangup), your script won't keel over when the network is severed and the trailing & symbol will run your script in the background.

    You can still view the output of your script, nohup will pipe the stdout to the nohup.out file. You can babysit the output in real time by tailing that output file:

    $ tail -f nohup.out
    

    quick note about the nohup.out file...

    nohup.out          The output file of the nohup execution if
                       standard  output is a terminal and if the
                       current directory is writable.
    

    or append the command with & to run the python script as a deamon and tail the logs.

    $ nohup python python_script.py > my_output.log &
    $ tail -f my_output.log