简体   繁体   English

使用systemd运行的Python脚本无法启动gedit

[英]Python script run with systemd cannot start gedit

I have the following Python script in /home/jack/Code/Service/main.py : 我在/home/jack/Code/Service/main.py具有以下Python脚本:

from subprocess import Popen

Popen(["/usr/bin/gedit"])

while True:
    pass

I am running it with this systemd service: 我正在使用此systemd服务运行它:

[Unit]
Description=Test

[Service]
Type=simple
Restart=no
User=jack
WorkingDirectory=/home/jack/Code/Service
ExecStart=/usr/bin/python3 main.py

[Install]
WantedBy=multi-user.target

When I run main.py from the command line with python3 main.py , it runs and gedit opens. 当我运行main.py命令行与python3 main.py ,它运行和gedit中打开。 When I start the systemd service and look at the logs, I see: 当我启动systemd服务并查看日志时,我看到:

mars 10 11:19:55 Ubuntu-Tower systemd[1]: Started Test.
mars 10 11:19:55 Ubuntu-Tower python3[8827]: Unable to init server: Could not connect: Connection refused
mars 10 11:19:55 Ubuntu-Tower gedit[8835]: cannot open display: 

Note that the gedit process actually does appear in the system monitor when the service runs (and only disappears when I stop the service), so this really seems to be a GUI-specific problem. 请注意, gedit进程实际上在服务运行时确实出现在系统监视器中(并且仅在我停止服务时才消失),因此这似乎确实是特定于GUI的问题。

What is going on, and how can I get the behavior I want? 发生了什么,如何获得所需的行为?

To open a window in X11, the windows system of Linux and others, you must specify a display. 要在X11,Linux和其他系统的Windows系统中打开窗口,必须指定显示。 Usually this is defined in the DISPLAY environment variable. 通常,这是在DISPLAY环境变量中定义的。 In my case it is set to ":0.0". 在我的情况下,它设置为“:0.0”。 If this variable is not set, the program does not know where to draw the window: 如果未设置此变量,则程序将不知道在何处绘制窗口:

marco$ DISPLAY= xeyes
Error: Can't open display:
marco$

Some programs allows you to specify the display via the -display parameter. 某些程序允许您通过-display参数指定显示。 This information alone is not enough: X11 incorporates an access control list of allowed clients that can connect to a specific server. 仅此信息是不够的:X11包含可以连接到特定服务器的允许客户端的访问控制列表。

marco$ su - test
Password:
test$ env | grep DISPLAY
DISPLAY=:0.0
test$ xeyes
No protocol specified
Error: Can't open display: :0.0

xhost is the tool to manipulate the acl: xhost是操纵acl的工具:

marco$ xhost +
access control disabled, clients can connect from any host
marco$ su - test
Password:
# disable X11 acl with xhost +
test:~$ xeyes
^C

In any case remember that the X11 server must be running to be able to open windows an you can incur in other kinds of errors if the server is not listening when the service is started (Unable to init server: Could not connect: Connection refused) 无论如何,请记住X11服务器必须正在运行才能打开窗口,并且如果服务器在启动服务时未在监听,则可能引发其他类型的错误(无法初始化服务器:无法连接:连接被拒绝)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM