Python 脚本作为 systemd 服务未正确启动

问题描述 投票:0回答:1

我已经构建了一个简短的 Python 来使用我的快捷方式启动应用程序。如果我使用终端启动它,它可以正常运行,但我试图将其应用为系统服务以始终开启。但我遇到错误

exited, status=203/EXEC
,我需要帮助来解决它。我得到的错误是
code=exited status=203/exec

这是代码:

from pynput import keyboard
import subprocess

def launch_firefox():
    subprocess.Popen(['firefox'])

def launch_terminal():
    subprocess.Popen(['kitty'])

pressed_keys = set()`
def on_press(key):
    global pressed_keys
    try:
        if key.char == 'q':
            if keyboard.Key.cmd_l in pressed_keys:
                launch_firefox()
    except AttributeError:
        if key == keyboard.Key.enter:
            if keyboard.Key.cmd_l in pressed_keys:
                launch_terminal()
        elif key == keyboard.Key.cmd_l:
            pressed_keys.add(key)



def on_release(key):
    global pressed_keys
    try:
        pressed_keys.remove(key)  # Remove released key from the set
    except KeyError:
        pass

with keyboard.Listener(
    on_press=on_press,
    on_release=on_release) as listener:
    listener.join()`

服务文件为:

[Unit]
Description = ...

[Service]
ExecStart=path of interpeter /path of the file.py
Restart=always
[Install]
WantedBy=multi.user.target

我使用 Arch,并使用 Openbox 和 Xorg。

编辑:我现在明白了

ImportError: this platform is not supported: ('failed to acquire X connection: Can\'t connect to display ":0": b
\'Authorization required, but no authorization protocol specified\\n\'', DisplayConnectionError(':0', b'Authorization required, but no authorizatio
n protocol specified\n'))
Mar 06 15:06:15 OSX python3[6722]: Try one of the following resolutions:
Mar 06 15:06:15 OSX python3[6722]:  * Please make sure that you have an X server running, and that the DISPLAY environment variable is set correctl
y
python python-3.x shell systemd
1个回答
0
投票

一般来说,系统服务无权访问您的图形环境。

您的图形登录并不是在整个系统中无处不在 - 这不再是 Windows 98,因此它是一个像任何其他服务一样启动的单独会话(因此服务之间的顺序很重要),并且它是专门为您的用户启动的(因此它不会甚至在您登录之前就存在),并且可以有多个(因此没有可供使用的服务的“默认”)。当然,它必须以正确的用户身份运行 - 您没有在服务中指定 User=,因此它以“root”身份运行。

可以使其作为系统服务工作,但这不是一个好的做法。

我正在尝试将其应用为系统服务以始终开启

您不需要将其成为系统服务即可始终在线。您可以将其作为用户服务,甚至只是每次都由您的桌面启动的常规非服务自动启动应用程序。

例如,您可以将单位放在

~/.config/systemd/user/
中,将其更改为具有
WantedBy=graphical-session.target
(在这种情况下不需要User=),然后以
systemctl --user start
启动它,依此类推。每用户服务管理器确实可以访问图形会话(尽管不是立即访问,所以不要使用default.target)。

如果您确实希望它成为系统服务,则需要 1)以正确的用户身份运行,2)拥有所有环境变量(至少

HOME
XDG_RUNTIME_DIR
DISPLAY
XAUTHORITY
) ,
WAYLAND_DISPLAY
...) – 不能保证是静态的,因此在服务中硬编码它们的当前值并不明智,并且列表并不详尽。执行此操作时,最好至少通过
systemd-run --user --service
启动应用程序,以便应用程序继承正确的环境。

© www.soinside.com 2019 - 2024. All rights reserved.