How to run python script after I close terminal?
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.
Andrew Nevskiy
Updated on September 18, 2022Comments
-
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 over 3 yearsCorrect: 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 over 3 yearsnice. 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 over 3 yearsYou 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 over 3 yearsWhile 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..
-