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

Run python program

main.py run --username desmond

Run python in background

nohup python main.py run --username desmond &

More:

  • 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)"

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.