I have a python script that I normally run it with this command:

(environment) python run.py

I want to run this script at start. (I'm using ubuntu) Here is my service:

[Unit]
Description=My Script Service
After=multi-user.target

[Service]
Type=idle

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py

[Install]
WantedBy=multi-user.target

BTW, I couldn't run this script, but I could run any script that is not inside environment. How can I run a python script at startup (virtualenv)?

sudo systemctl status user_sent
● user_sent.service - Mail Service
Loaded: loaded (/lib/systemd/system/user_sent.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since xxxxx 16:30:20 MSK; 3s ago
Process: 3713 ExecStart=/usr/bin/python run.py (code=exited,   status=200/CHDIR)
Main PID: 3713 (code=exited, status=200/CHDIR)
up vote 12 down vote accepted

Your unit file is correct. If you want to run any python file under an venv you just need to reference the python binary in the venv directory like you did with /home/user/anaconda3/bin/python

[Unit]
Description=My Script Service
After=multi-user.target

[Service]
Type=idle

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py

[Install]
WantedBy=multi-user.target

What sticks out is the reason your unit fails: code=exited, status=200/CHDIR. This most likely indicates an issue within your script.

If you want to debug that, you would do the following:

  1. Run the command you added to ExecStart= exactly like that under root to see, if the issue is caused by your script.
  2. If that runs without errors, look at the journal with journalctl -u <unit_name>. That should give you some more information on issues with your unit.

Post Scriptum

Both of the following [Service] options work:

ExecStart=/home/user/anaconda3/bin/python /home/user/space/run.py

or

WorkingDirectory=/home/user/space
ExecStart=/home/user/anaconda3/bin/python run.py

The only difference is that relative calls in your script run from different directories. So if your script contains a line open("my_file", "w"), in the first example it would create a file /my_file and the second a file /home/user/space/my_file.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.