Search code examples
flaskcharacter-encodingpython-3.5synology

Python: Running my program on synology nas as a task throws UnicodeEncodeError


I just developed a small Server for some testing with the Spotify-API. It is supposed to run on a synology nas. As I don't want the App to be run using a admin account, I created a new User. Then I created a task in the synology DSM and used that to run my Application as the newly created User. At first I had a error with wrong Encodings, but I added the encoding in the headers of my files # -*- coding: utf-8 -*- after that it worked.

Until I came to the line containing a UTF-8 encoded "ä".

Traceback (most recent call last):
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/var/services/homes/svc_spotify/.local/lib/python3.5/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/volume1/Programmieren/Python/SpotifyToExcel/spotifyAuth.py", line 73, in spotify
    log("Token erhalten, Server f\xe4hrt herunter")
  File "/volume1/Programmieren/Python/SpotifyToExcel/spotifyAuth.py", line 24, in log
    logFile.write("{}: {}\n".format(datetime.datetime.now(), text))
UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 52: ordinal not in range(128)

then I added export PYTHONTEXTENCODING=utf-8 to my script that starts the Program. Doesn't work either.

Now the weird part: running it as my normal user on a ssh shell works as intended. And even running it using sudo -H -u svc_spotify python3 spotifytoexcel.py works as intended.

Is there another way I can force an encoding or maybe someone knows how synology runs tasks and why that changes the default encoding for python.

Visual Studio Code shows UTF-8 as the encoding of all my files.


Solution

  • After improving my googleing skills I found another answer on overflow and it turns out, that I needed to set my language in my tasks Script export LANG=en_US.utf8 now it all works.

    My script now starts like this:

    export PYTHONIOENCODING=utf8
    export PYTHONTEXTENCODING=utf8
    export LANG=en_US.utf8