Run persistent python script from systemd?

I have a python script that decodes input from a USB device and sends commands to a PHP script. The script works great when launched from the console, but I need it to run at startup.

I created a systemd service to run a script that seems to work fine, except that the systemctl start service-name process never returns me to the command line. While it is working, I can interact with the input device, as expected. However, if I systemctl start process using ctr-z, the script remains operational for a few seconds.

Here is the .service file I wrote:

 [Unit] After=default.target [Service] ExecStart=/usr/bin/python /root/pidora-keyboard.py [Install] WantedBy=default.target 

and here is my python script:

 #!/usr/bin/env python import json, random from evdev import InputDevice, categorize, ecodes from urllib.request import urlopen dev = InputDevice('/dev/input/event2') def sendCommand(c): return json.loads(urlopen("http://127.0.0.1/api.php?command="+c).read().decode("utf-8")) def getRandomStation(): list = sendCommand('stationList') list = list['stations'] index = random.randint(0, (len(list)-1)) print(list[index]['id'] + " - " + list[index]['name']) sendCommand('s' + list[index]['id']) print(dev) for event in dev.read_loop(): if event.type == ecodes.EV_KEY: key_pressed = str(categorize(event)) if ', down' in key_pressed: print(key_pressed) if 'KEY_PLAYPAUSE' in key_pressed: print('play') sendCommand('p') if 'KEY_FASTFORWARD' in key_pressed: print('fastforward') sendCommand('n') if 'KEY_NEXTSONG' in key_pressed: print('skip') sendCommand('n') if 'KEY_POWER' in key_pressed: print('power') sendCommand('q') if 'KEY_VOLUMEUP' in key_pressed: print('volume up') sendCommand('v%2b') if 'KEY_VOLUMEDOWN' in key_pressed: print('volume down') sendCommand('v-') if 'KEY_CONFIG' in key_pressed: print('Random Station') getRandomStation() 

how to make a script run asynchronously from a service file so that the start command can complete and the script can continue to run in the background?

+6
source share
2 answers

You specified both After=default.target and WantedBy=default.target . This is not solvable.

WantedBy indicates that the target will enable this service at startup, but after that means that the named target will be launched before the service starts!

Most likely you will not need After=default.target and should remove this.


I also suggest that you explicitly specify the Type= service. Although the default is currently simple (which should work for what you are doing), older versions of systemd may behave differently.

 [Service] Type=simple 
+3
source

How about usig nohup? http://en.wikipedia.org/wiki/Nohup nohup is a POSIX command to ignore the HUP (hangup) signal. The HUP (hang) signal is consistent with how the terminal warns of dependent logout processes.

+1
source

Source: https://habr.com/ru/post/951154/


All Articles