英文:
How to set the LANG for a python script running through systemd?
问题
在运行程序的服务器上, 默认编码是 latin-1,当我尝试运行一个Python脚本时,出现类似 'latin-1' codec can't encode characters in position 的错误。
我知道你可以使用 dpkg-reconfigure locales 更改默认区域设置,但对我来说另一种方式更方便:
LANG=en_US.utf8 python3.11 main.py
现在问题是:在使用 systemctl 运行脚本时是否有办法设置 LANG?
我使用这个 script.service:
[Unit]
Description=My Script
After=syslog.target
[Service]
Type=simple
User=username
Group=sudo
WorkingDirectory=/home/username/project_dir/
ExecStart=/usr/bin/python3.11 main.py
[Install]
WantedBy=multi-user.target
英文:
On the server where I run the program the default encoding is latin-1, and when I try to run a python script I get an error like 'latin-1' codec can't encode characters in position, etc.
I know you can change the default locale with dpkg-reconfigure locales, but for me the other way is more convenient:
LANG=en_US.utf8 python3.11 main.py
Now the question remains: is there any way to put the LANG when I run the script using the systemctl?
I use this script.service:
[Unit]
Description=My Script
After=syslog.target
[Service]
Type=simple
User=username
Group=sudo
WorkingDirectory=/home/username/project_dir/
ExecStart=/usr/bin/python3.11 main.py
[Install]
WantedBy=multi-user.target
答案1
得分: 0
如果你想简单地覆盖 LANG 变量,你可以在服务定义中添加一个 "Environment" 行,例如:
[Unit]
Description=我的脚本
After=syslog.target
[Service]
Type=simple
User=username
Group=sudo
WorkingDirectory=/home/username/project_dir/
Environment="LANG=en_US.utf8"
ExecStart=/usr/bin/python3.11 main.py
[Install]
WantedBy=multi-user.target
你也可以将 "ExecStart" 替换为以下方式的调用:
ExecStart=/usr/bin/env LANG=en_US.utf8 /usr/bin/python3.11 main.py
英文:
If you want to simply override the LANG variable, you can add an Environment line to the service definition e.g.
[Unit]
Description=My Script
After=syslog.target
[Service]
Type=simple
User=username
Group=sudo
WorkingDirectory=/home/username/project_dir/
Environment="LANG=en_US.utf8"
ExecStart=/usr/bin/python3.11 main.py
[Install]
WantedBy=multi-user.target
You can also replace ExecStart with an invocation of env…
ExecStart=/usr/bin/env LANG=en_US.utf8 /usr/bin/python3.11 main.py
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论