从systemd运行持久的python脚本?

我有一个python脚本解码来自USB设备的输入并将命令发送到PHP脚本.从控制台运行时,该脚本运行良好,但我需要它在启动时运行.

我创建了一个systemd服务来启动脚本,看起来效果很好,除了systemctl start service-name进程永远不会让我返回命令提示符.在它运行时,我可以完全按照预期与输入设备进行交互.但是,如果我使用ctr-z退出systemctl启动进程,则脚本只会运行几秒钟.

这是我写的.service文件:

[Unit]
After=default.target

[Service]
ExecStart=/usr/bin/python /root/pidora-keyboard.py

[Install]
WantedBy=default.target

这是我的python脚本:

#!/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()

如何使脚本从服务文件异步运行,以便启动命令可以完成,脚本可以继续在后台运行?

最佳答案
您已指定After = default.target和WantedBy = default.target.这是不可解决的.

WantedBy指定目标在启动时将包含此服务,但After意味着在启动此服务之前确保命名目标已启动!

很可能你不需要After = default.target并且应该删除它.

我还建议您明确指定服务Type =.虽然默认设置目前很简单(适用于您正在做的事情),但旧版本的systemd可能表现不同.

[Service]
Type=simple

相关文章

linux常用进程通信方式包括管道(pipe)、有名管道(FIFO)、...
Linux性能观测工具按类别可分为系统级别和进程级别,系统级别...
本文详细介绍了curl命令基础和高级用法,包括跳过https的证书...
本文包含作者工作中常用到的一些命令,用于诊断网络、磁盘占满...
linux的平均负载表示运行态和就绪态及不可中断状态(正在io)的...
CPU上下文频繁切换会导致系统性能下降,切换分为进程切换、线...