Search code examples
pythonlinuxubuntusystemdsystemctl

How to set the LANG for a python script running through systemd?


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

Solution

  • 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