0

I am trying to make a project written on Python work on a server. I created the following service file:

[Unit]
Description=My bot service
After=multi-user.target
[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python3.10 /home/path/to/bot.py
[Install]
WantedBy=multi-user.target

But this code doesn't work. If I check service status, it returns the following:

● test.service - My bot service
     Loaded: loaded (/etc/systemd/system/test.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Fri 2022-10-21 08:16:07 UTC; 15s ago
    Process: 156695 ExecStart=/usr/bin/python3.10 /home/path/to/bot.>
   Main PID: 156695 (code=exited, status=1/FAILURE)

Oct 21 08:16:07 instance-1 systemd[1]: test.service: Scheduled restart job, restart coun>
Oct 21 08:16:07 instance-1 systemd[1]: Stopped My bot service.
Oct 21 08:16:07 instance-1 systemd[1]: names.service: Start request repeated too quickly.
Oct 21 08:16:07 instance-1 systemd[1]: test.service: Failed with result 'exit-code'.
Oct 21 08:16:07 instance-1 systemd[1]: Failed to start My bot service.

When I execute the bot directly (/usr/bin/python3.10 /home/path/to/bot.py), it works.

When I run a simple Python script as a service, it also works.

I just don't understand what can cause the problem inside the project. Adding WorkingDirectory parameter into the configurational file didn't change anything

1 Answer 1

0

bot.py is returning 1.

You'll need to inspect the code to see in which conditions it could exit with that code.

The first thing I would do is remove Restart=always. You can see that your script failed, then restarted, then restarted, then restarted, then stopped trying. Most likely, if it fails the first time, it won't succeed later. So there is little need for this line until you have things working well enough. All it does is pollute your output and cause confusion during development. Without this systemctl status may have given your last few lines of stdout.

The next thing I would do is start this service and check the journal:

$ sudo systemctl start test.service
$ journalctl -u test.service --since "5 minutes ago"

That may give you stdout or stderr clues about what happens. Specifically check for exception traces.

If you don't have any output in the journal, then it may be because python exited before its buffer could be flushed. Use python's -u option to ensure the output is unbuffered:

ExecStart=/usr/bin/python3.10 -u /home/path/to/bot.py

Finally, if this bot creates a window and has a GUI, there are special steps you need to take (run this on the --user bus or set DISPLAY= environment). I can give more info if you expect a GUI. This is a super common reason why people have "I can run it, but systemd can't" issues.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .