Hyperion
Hyperion

Reputation: 121

Run Python headless on local server

So, here is my little problem:

I have a small python program and have to run it 24/7 with internet access. So using my laptop is not really a solution. But I can use a local server. My program is saved on the server. Is there a way to start the program headless on the server, so it can run for a long period of time?

Thanks

Upvotes: 1

Views: 3912

Answers (1)

Azsgy
Azsgy

Reputation: 3317

This post assumes you are using linux. If this is not the case, I will still keep this answer around for anyone else. The general Principles will apply to any OS regardless.

While setsid is one way to put a program into the background, it is usually not what you want for a number of reasons:

  • If you ssh into the server again, there is no easy way to see the output of the program. Any output will not be kept.
  • If the program crashes, it won't be restarted.
  • If the server reboots, it won't be started.
  • There is no easy way to see the status, stop or restart it.

One slightly better method would be to use tmux (or the older screen). These can be used to detach a process, but still have access to it's output. (see this answer).

However, if you want to do things correctly, you should use a process manager/supervisor, such as systemd or supervisord.

For systemd, you can create the following file: /etc/systemd/system/yourprogramname.service

Inside it, place the following text:

[Unit]
Description=YourDescription

[Service]
ExecStart=/usr/bin/python3 /your/full/script/location.py
Restart=always

[Install]
WantedBy=multi-user.target

(These files support a number of additional options, you can view them at: http://0pointer.de/public/systemd-man/systemd.service.html)

Then reload the units with systemctl daemon-reload and enable your unit at boot with systemctl enable yourprogramname.service.

You can then:

  • Start it: systemctl start yourprogramname
  • Retart it: systemctl restart yourprogramname
  • Stop it: systemctl stop yourprogramname
  • Get the status: systemctl status yourprogramname
  • View the full logs: journalctl -u yourprogramname

(these commands all require sudo)

Upvotes: 4

Related Questions