Ubuntu: Nohup Run Python as Background Process and Capture Log to File

October 7, 2019

Run python program

main.py run --username desmond

Run python in background

nohup python main.py run --username desmond &


  • nohup [COMMAND] &: run as background
  • python -u: disable output buffering (to ensure exception are shown immediately)
  • [COMMAND] > /logs/main.log 2>&1: capture std and err output into log
  • $! > run.pid: save process id into file (pid can be use to check if process is still alive, and kill it if necessary)
nohup python -u main.py run --username desmond > /logs/main.log 2>&1 & echo $! > desmond.pid

Check log

tail -f /logs/main.log

Check pid is running

ps -p "$(cat desmond.pid)"
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.