![](/img/trans.png)
[英]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.