如何为通过systemd运行的Python脚本设置LANG?

huangapple go评论96阅读模式
英文:

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 更改默认区域设置,但对我来说另一种方式更方便:

  1. LANG=en_US.utf8 python3.11 main.py

现在问题是:在使用 systemctl 运行脚本时是否有办法设置 LANG

我使用这个 script.service

  1. [Unit]
  2. Description=My Script
  3. After=syslog.target
  4. [Service]
  5. Type=simple
  6. User=username
  7. Group=sudo
  8. WorkingDirectory=/home/username/project_dir/
  9. ExecStart=/usr/bin/python3.11 main.py
  10. [Install]
  11. 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:

  1. 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:

  1. [Unit]
  2. Description=My Script
  3. After=syslog.target
  4. [Service]
  5. Type=simple
  6. User=username
  7. Group=sudo
  8. WorkingDirectory=/home/username/project_dir/
  9. ExecStart=/usr/bin/python3.11 main.py
  10. [Install]
  11. WantedBy=multi-user.target

答案1

得分: 0

如果你想简单地覆盖 LANG 变量,你可以在服务定义中添加一个 "Environment" 行,例如:

  1. [Unit]
  2. Description=我的脚本
  3. After=syslog.target
  4. [Service]
  5. Type=simple
  6. User=username
  7. Group=sudo
  8. WorkingDirectory=/home/username/project_dir/
  9. Environment="LANG=en_US.utf8"
  10. ExecStart=/usr/bin/python3.11 main.py
  11. [Install]
  12. WantedBy=multi-user.target

你也可以将 "ExecStart" 替换为以下方式的调用:

  1. 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.

  1. [Unit]
  2. Description=My Script
  3. After=syslog.target
  4. [Service]
  5. Type=simple
  6. User=username
  7. Group=sudo
  8. WorkingDirectory=/home/username/project_dir/
  9. Environment="LANG=en_US.utf8"
  10. ExecStart=/usr/bin/python3.11 main.py
  11. [Install]
  12. WantedBy=multi-user.target

You can also replace ExecStart with an invocation of env…

  1. ExecStart=/usr/bin/env LANG=en_US.utf8 /usr/bin/python3.11 main.py

huangapple
  • 本文由 发表于 2023年2月14日 19:40:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定