1

I just got a debian 8 VPS and I'm trying to run a python script as a service, I wrote this (everithing was done via ssh logged as root) :

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

[Service]
Type=idle
ExecStart=/usr/bin/python /web/cmcreader/test.py > /web/cmcreader/test.log 2>&1

[Install]
WantedBy=multi-user.target

I've put it in /lib/systemd/system I then chmoded it :

chmod 644 /lib/systemd/system/cmcreader.service

I then tried to activate it using :

systemctl daemon-reload
systemctl enable cmcreader.service

however the last command returns (enable) :

Failed to execute operation: Invalid argument

What did I do wrong? Thanks.

2 Answers2

5

Starting at man systemd.directives you can find the docs for any systemd directive. Here you can find that ExecStart= is documented in man systemd.service.

The docs there say:

redirection using "<", "<<", ">", and ">>", pipes using "|", running programs in the background using "&", and other elements of shell syntax are not supported.

They are also not usually needed. systemd already runs apps in the background by default, so you don't need &. It also automatically captures output to STDOUT and STDERR and logs it for you, so you don't need to redirect the output to a log file either.

Just use journalctl -u cmcreader to view the logs for your service, or journalctl to view all the logs.

If you aren't sure about the syntax of a systemd file, you can use:

systemd-analyze verify ./path/to/your.service

Also, service files you create go in /etc/systemd/system. The /lib directory is for service file installed by packages, not humans.

Finally, enable doesn't start the service, it just runs the [Install] section, setting your app to start at boot.

To start the service use systemctl start your.service.

1

The problem is that you are trying to use shell redirection operators - systemd will not implicitly run the ExecStart line in a shell.

What it does do, is run the program you specify (/usr/bin/python in your example) with everything else being the argument to said program. You get an invalid argument error, because the > /web/cmcreader/test.log 2>&1 part is an invalid argument to python.

While I certainly recommend that you simply use journalctl as anwsered by @mark-stosberg and remove everything from the redirection forward, if you really want your python script to write out to a file, you have a couple of options:

  • rewrite your python to actually write to the logfile
  • have systemd run a bash script that runs the python script and redirects the outputs
  • have systemd run bash explicitly a la ExecStart=bash -c "/usr/bin/python /web/cmcreader/test.py > /web/cmcreader/test.log 2>&1"

Again, I do not really recommend these options - especially not the last one.

user6075516
  • 898
  • 6
  • 11