How to run python script after I close terminal?

6,066

You can use the nohup command:

nohup python test.py &

This will continue to run the command even after you close your ssh session. nohup catches the SIGHUP signal when the controlling terminal process dies to ensure the command continues to run.

Simply using python test.py & might also work if your shell ignores SIGHUP. In that case, your python process would be re-parented to the init process and continue to run. But this relies on the shell.

For example, bash has an option huponexit - when it's off, the re-parenting would happen; when it's on, SIGHUP will be sent to the background processes. So nohup is the way to go.

Share:
6,066
Andrew Nevskiy
Author by

Andrew Nevskiy

Updated on September 18, 2022

Comments

  • Andrew Nevskiy
    Andrew Nevskiy over 1 year

    Sorry for the lame question, I faced VDS for the first time in my life. I've set everything up, installed all python modules the app needed and after I run my script like

    python test.py
    

    it works just ok, but after I close my ssh window that i used for remote connect to my VDS - the script doesn't work anymore.

    How to run my test.py to make it work 24\7?

    • user535733
      user535733 over 3 years
      Correct: Closing the ssh session terminates all child processes of that session. There are several ways around it. The "best" (for me) is to use a systemd service, so the session parent is root instead of you. Another alternative is to use the screen or tmux applications to create a persistent tty that you can attach to and detatch from.
    • Andrew Nevskiy
      Andrew Nevskiy over 3 years
      nice. As far as I understood i have to create a "Demon" but can't find any good instruction for ubuntu 20. Some tutorials say "put the .conf file to /etc/init"... but i have only "init.d" in that folder. And it doesn't want to run.. root@static:/home# sudo service tbot restart Failed to restart tbot.service: Unit tbot.service not found.
    • user535733
      user535733 over 3 years
      You don't need to create a daemon (not "demon") -- that terminology is obsolete. The equivalent is an always-running systemd service, one of several types of service. /etc/init.d is a sysvinit thing, two init systems ago. I don't know where you're getting all this old 2000-2012-era information, but stop going there. Advice: 1) Look up how to use screen and try it that way. 2) Then look up how to do it the systemd service way, and try that, too. If you can figure out one, you can figure out both. Keep notes - both are handy skills.
    • Raffa
      Raffa over 3 years
      While a system service is the permanent solution. A temporary and quick fix is to run your command like this python test.py & see here for explanation and extra info..