簡體   English   中英

使用systemd運行的Python腳本無法啟動gedit

[英]Python script run with systemd cannot start gedit

我在/home/jack/Code/Service/main.py具有以下Python腳本:

from subprocess import Popen

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

while True:
    pass

我正在使用此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

當我運行main.py命令行與python3 main.py ,它運行和gedit中打開。 當我啟動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: 

請注意, gedit進程實際上在服務運行時確實出現在系統監視器中(並且僅在我停止服務時才消失),因此這似乎確實是特定於GUI的問題。

發生了什么,如何獲得所需的行為?

要在X11,Linux和其他系統的Windows系統中打開窗口,必須指定顯示。 通常,這是在DISPLAY環境變量中定義的。 在我的情況下,它設置為“:0.0”。 如果未設置此變量,則程序將不知道在何處繪制窗口:

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

某些程序允許您通過-display參數指定顯示。 僅此信息是不夠的: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是操縱acl的工具:

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

無論如何,請記住X11服務器必須正在運行才能打開窗口,並且如果服務器在啟動服務時未在監聽,則可能引發其他類型的錯誤(無法初始化服務器:無法連接:連接被拒絕)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM