How to run python script in background after i logout

Steve M sjmaster at gmail.com
Sun Jul 24 15:59:04 EDT 2005


Harlin Seritt wrote:
> I have a remote linux server where I can only access it via ssh. I have
> a script that I need to have run all the time. I run like so:
>
> python script.py &
>
> It runs fine. When I log off ssh I notice that the script died when I
> logged off. How do I make sure it stays running?

You might also check out the extremely cool screen program. It lets you
have multiple virtual terminal sessions from one connection, and detach
them all and logout, then login later and re-attach them. I typically
use 'screen -D -R' which will re-attach if there is a set of sessions
to re-attach, or otherwise start a new one.

Then you can have a dedicated window for your script.py (you don't even
need to run it in the background of the shell with '&') and you can
just detach the screen before you logout. Later you can log back in,
reattach, check for any output (you can use print statements for debug
info, etc.).

Since it can be tricky getting started, I'll tell you briefly, there is
a command key, which you use to send commands to the screen program.
Anything other than command key will be passed through to whatever
program is running, e.g. the bash shell or whatever. The default
command key is ctrl-a. So you would do 'ctrl-a c' to create a new
virtual window, 'ctrl-a 1', 'ctrl-a 2', etc. to switch between virtual
windows, and 'ctrl-a d' to detach your session. This brings you back to
your original ssh login shell. Incidentally, if you do a 'ps aux' here
you'll see one of the programs is 'SCREEN' owned by root; this is the
process that is keeping alive all your other processes and that
persists when you logout and allows you to reattach later.

A couple of problems I've had are first, that ctrl-a is also the emacs
command to go to the beginning of the line, which I use all the time.
So I've sometimes rebound the screen command key (I've tried ctrl-[
since I dont' ever seem to use that for anything else, but I don't
think it works entirely perfectly, especially in combination with the
next problem.). Another is that when I use putty.exe from Windows for
my ssh client, I can't get scroll-back buffers to work correctly with
screen. (Screen is really powerful with its own scrollback buffers and
screendumps and stuff but I don't have time to get into all that or
even learn it sometimes. I wish I were more a master of it since its
such a great program.)

Another alternative is to daemonize your program, but I don't know how
to do that off the top of my head.




More information about the Python-list mailing list