I have a Flask application (Linux, Apache with mod_wsgi, Python 3) which calls a shell script with some arguments. When there are any non-ascii characters in the subprocess.run()
command arguments, following error occurs in the application:
'ascii' codec can't encode characters in position 5-6: ordinal not in range(128)
I spent a lot of time trying to fix it.
No such problem exists in the command line, only in the application.
The entire application's output is in Unicode and there are no problems with it. After some research I came to the conclusion the problem is with the "filesystem encoding".
I have added some logging statements to my run.wsgi
script. The FS encoding was 'ascii' indeed (and 'utf-8' in the command line).
In the next step I found this article How to change file system encoding via python?
The Apache httpd server was started with LANG=C
in its environment. I have changed it to C.UTF-8
despite warnings in /etc/sysconfig/httpd
. That did not help, the FS encoding was still 'ascii'. I have then even monkey-patched the sys.getfilesystemencoding()
to lambda: 'utf-8'
. But the error is still there.
I have properly restarted the httpd service after each change.
I'm at my wits' end.
- Is my problem really caused by the FS encoding?
- If yes, why my attempts to change it to utf-8 failed?
- Most importantly: How can I solve this issue?
UPDATE1:
code snippet:
import subprocess as sub
cmdresult = sub.run(
[SCRIPT, tid, days, name],
stdin=sub.DEVNULL, stdout=sub.PIPE, stderr=sub.DEVNULL,
encoding='ascii', # 'utf-8' will not help, this affects stdin, stdout I/O only
check=True)