Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to restart python script if it ends? (Ubuntu 18.04)

I have a few Discord bots written in Python that will stop for whatever reason after a few hours. I want a way to monitor them and restart them if they go down. I've already looked for a few solutions including a bash script, crontab, and systemd, but none of them seem to be working for me.

Even with a simple while true bash script, it will go down for some reason. The crontab won't run because of what I assume are environment issues, and apparently systemd is only for services?

All of the python scripts are located in /home/username/folder/script.py

I would also like to be able to easily pause the service that restarts the scripts, because occasionally I will have to update the code with git.


1 Answers

I figured out how to solve my problem with systemd.

First navigate to:

/etc/systemd/system

Then create a new service as root:

sudo nano example.service

Make your service file like this:

[Unit]
Description=Restarts example.py if it closes

[Service]
User=your username
WorkingDirectory=/directory/of/script
ExecStart=/usr/bin/python3 /directory/of/script/example.py
Restart=always

[Install]
WantedBy=multi-user.target

Then type this in to have systemd reload the service files.

sudo systemctl daemon-reload

Then you can start your service:

sudo systemctl start example.service

Finally, check the status of your service:

sudo systemctl status example.service

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!