[英]Linux / Raspberry Pi OS - Systemd not working with python3 script using OS module that accesses enviroment variable
[英]Linux / Raspberry Pi OS - Setting environment variable that will work with a systemd service
我昨天問了這個問題,本質上是關於運行由我命名為mqtt.service
的 systemd 服務運行的 python3 腳本(使用在etc/enviroment中設置的環境變量)。
我從該問題的答案中獲得了一些有用的信息,表明默認情況下/etc/environment
中的環境變量在systemd中不可訪問,並且該答案鏈接到該問題,詳細說明了您可以采取哪些步驟來允許 systemd 服務查看您選擇的環境變量。
到目前為止,我已經嘗試了以下方法:
在我的服務中,我嘗試添加EnvironmentFile=/etc/environment
,其中包含我的環境變量: export DEVICE_ID="TEST1"
。 我還嘗試使用systemctl edit mqtt.service
創建mqtt.service.d/override.conf
文件,該文件也設置了EnvironmentFile=/etc/environment
。
接下來我嘗試直接在mqtt.service
以及mqtt.service.d/override.conf
文件中設置Environment=$DEVICE_ID
。
然后我嘗試了上述所有方法,但更改了$DEVICE_ID
環境變量的設置位置。 到目前為止,我已經嘗試在etc/profile
中將其設置為export DEVICE_ID="TEST1"
的值。
最后,我還嘗試在/etc/profile.d/device_id.sh
中創建一個device_id.sh
文件,其值為 export DEVICE_ID=TEST1
。 當我嘗試運行mqtt.service
時,這給了我以下結果:
user@computer:/etc/profile.d $ sudo systemctl status mqtt.service
● mqtt.service - Arms the mqtt.py script that will alert if the device is moved
Loaded: loaded (/etc/systemd/system/mqtt.service; disabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/mqtt.service.d
└─override.conf
Active: activating (auto-restart) (Result: exit-code) since Fri 2022-08-12 14:49:52 BST; 4s ago
Process: 12941 ExecStart=python3 /scripts/mqtt.py (code=exited, status=1/FAILURE)
Main PID: 12941 (code=exited, status=1/FAILURE)
CPU: 551ms
user@computer:/etc/profile.d $ sudo systemctl status mqtt.service
● mqtt.service - Arms the mqtt.py script that will alert if the device is moved
Loaded: loaded (/etc/systemd/system/mqtt.service; disabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/mqtt.service.d
└─override.conf
Active: activating (auto-restart) (Result: exit-code) since Fri 2022-08-12 14:49:52 BST; 4s ago
Process: 12941 ExecStart=python3 /scripts/mqtt.py (code=exited, status=1/FAILURE)
Main PID: 12941 (code=exited, status=1/FAILURE)
CPU: 551ms
user@computer:/etc/profile.d $
在嘗試運行mqtt.service
時,我在上面嘗試的所有操作都給了我類似的錯誤消息。
我真的在為此苦苦掙扎,我不知道我是否錯過了某些東西,或者我想要實現的目標是不可能的?
正如您提供的鏈接的第二個答案和man environment.d
中所解釋的,文件/etc/environment
用於在用戶服務環境中設置變量,即使用systemctl --user start...
的服務。 您正在使用系統服務,因此如果要包含此文件,則需要設置
[Service]
EnvironmentFile=/etc/environment
你現在可能已經有了。 確保它位於正確的部分。 您還需要在編輯單元文件后運行sudo systemctl daemon-reload
。
但是,手冊頁還解釋說,環境文件中的行格式非常有限。 特別是 shell 命令export
是不允許的。 雖然沒有提到,雙引號是允許的,但不是必需的。 所以你應該嘗試像這樣的條目
DEVICE_ID=TEST1
您應該在編輯此文件后執行systemctl --user daemon-reload
以對其進行解析和檢查錯誤,但您需要在各種系統日志文件之一中查找錯誤消息。 您可以使用systemctl --user show-environment
查看任何更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.