T
T
timka2282021-02-22 18:01:38
Python
timka228, 2021-02-22 18:01:38

How to make a Python script run automatically on Ubuntu?

There is a small vds on ubuntu 16.04 running python scripts. They all work in screen. So there is one script that performs the function of a telegram bot. It periodically crashes due to an error (like longpool falls off). Is it possible to somehow make the script automatically run when it crashes? And How? It is also desirable that when the server is rebooted, the scripts also run themselves.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dr. Bacon, 2021-02-22
@timka228

systemd

D
Dmitry, 2021-02-22
@dmtrrr

1. supervisord.org
2. docker

V
Victor, 2021-02-24
@Victor_M

Run the script as a Service.
I have done this:
1. The user-owner of the script's home directory is telebot, root rights are not required to work
2. Create the telebot.service file in the /etc/systemd/system directory
File contents:

[Unit]
Description=Service for Telegram bot main. From user telebot
After=network.target
# Для запуска сервиса нужен запущенный сервис MySQL (т.к. работаем с базой данных, расположенной на этом же сервере)
After=mysql.service
Requires=mysql.service

[Install]
WantedBy=multi-user.target

[Service]
# Даем знать systemd, что этот сервис представляет из себя лишь 1 процесс.
# Ожидается, что процесс, настроенный с помощью ExecStart= является основным процессом службы
Type=simple
# Устанавливаем рабочую дирректорию службы
WorkingDirectory=/home/telebot/bot_prod/
# Указаываем пользователя и группу для работы службы
User=telebot
Group=telebot
# Должна ли служба считаться активной, даже если все ее процессы завершены
RemainAfterExit=no
# Выполнить эту команду при запуске сервиса.
ExecStart=python3 /home/telebot/bot_prod/bot.py
# Говорим, что нужно перезапускать сервис, если вдруг он умер
Restart=on-failure
# Таймаут на включение и выключение
TimeoutSec=60

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question