我有一个python脚本,它解码来自usb设备的输入并将命令发送到php脚本。当从控制台运行时,脚本工作得很好,但我需要它在启动时运行。
我创建了一个systemd服务来启动脚本,它似乎工作得很好,只是systemctl start service-name
进程从不将我返回到命令提示符。当它运行时,我可以与输入设备进行交互,正如预期的那样。但是,如果我使用ctr-z退出systemctl start
进程,脚本只会保持运行几秒钟。
这是我写的.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()
如何使脚本从服务文件异步运行,以便start命令可以完成,并且脚本可以在后台继续运行?
使用nohup怎么样? http://en.wikipedia.org/wiki/Nohup nohup是一个POSIX命令,用于忽略HUP(挂断)信号。HUP(hangup)信号按照惯例是终端警告相关进程注销的方式。
您同时指定了
After=default.target
和WantedBy=default.target
。这是无法解决的。WantedBy指定目标在启动时将包含此服务,但After表示在启动此服务之前确保命名目标已启动!
很可能您不需要
After=default.target
,应该删除它。我还建议您显式地指定服务
Type=
。虽然默认值是当前的simple
(这应该对您所做的工作有效),但较旧版本的systemd的行为可能有所不同。相关问题 更多 >
编程相关推荐