Python script not running from systemd-unit

Hello dear Nix Wizards

I try to run a systemd service that is executing a python script.

For some reason I get this error:

line 39: syntax error near unexpected token `('
line 39: `with open(ad_description_path, 'r') as file:'

Here’s the code that matters in the error message:

systemd.services."obei-automation" = {
  wantedBy = [ "default.target" ];
  partOf = [ "default.target" ];
  script = ''
#!/run/current-system/sw/bin/python
# coding: utf-8

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from time import sleep

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

import os

...

ad_description_path = '/home/usr/Documents/ad_description.txt'

...

with open(ad_description_path, 'r') as file:
    data = file.read()
data = data.split('##')

Would be very much appreciated to here some suggestions!

Likely the shebang is not right. script may add a bash shebang.
Check systemctl cat obei-automation and read the file pointed to by Exec

1 Like

concider the nix writers: Nix-writers - NixOS Wiki

1 Like

thank you @pbsds this is the solution. I created a little example to test:

systemd.services."automation" = {
  enable = true;
  wantedBy = [ "default.target" ];
  partOf = [ "default.target" ];
  script = ''
${pkgs.writers.writePython3 "my-python-script.py" { libraries = [ ]; } ''
      import time
      print("hello world")
      time.sleep(3)
    ''}
  '';
};

and the timer:

systemd.timers."automation" = {
  enable = true;
  wantedBy = [ "timers.target" ];
    timerConfig = {
      OnCalendar = "minutely";
      Unit = "automation.service";
    };
};

thank you very much!

1 Like

I think you can change this to

  script = ${pkgs.writers.writePython3 "my-python-script.py"
    { libraries = [ ]; }
    ''
      import time
      print("hello world")
      time.sleep(3)
    '';

As the writers return a derivation, which automatically coerces to its own output path as a string wherever a string is expected.

1 Like

@iFreilicht
perfect, less complication is always welcome, thank you!