0

Trying to pass some non-ASCII texts to a Python Script through arguments.

demo.php

echo shell_exec("python3 demo.py 学校");

demo.py

import sys
print(sys.getfilesystemencoding())
print(sys.argv)

When I try to run it in console (php demo.php), it gives the correct result.

UTF-8
['demo.py', '学校']

But when I try to run it from a browser, it inserts a \xdc before each non-ASCII byte:

ascii
['demo.py', '\udce5\udcad\udca6\udce6\udca0\udca1']

How can I force the filesystem encoding with PHP script?

Failed attempts

  • All kinds of set_locale settings
    • set_locale(LC_ALL, "C.UTF-8");
    • set_locale(LC_ALL, "en_US.UTF-8");
    • set_locale(LC_ALL, "en_US.utf8");
    • etc.
10
  • It seems it's Python 2 on the server. Jan 11, 2017 at 15:19
  • @NizamMohamed Python 3.5.2 both of the times, and both on the same machine.
    – Eana Hufwe
    Jan 11, 2017 at 15:39
  • "run it from a browser" what does that mean? Jan 11, 2017 at 15:44
  • @NizamMohamed , Run the PHP file through HTTP. Something like open up http://127.0.0.1/demo.php. (Server hosted with Apache 2)
    – Eana Hufwe
    Jan 11, 2017 at 16:21
  • do check response Content-Type from the browser. It must be text/plain or text/html with charset=utf-8 otherwise the browser can't decode the bytes. or just post response headers from browser's developer tools. Jan 11, 2017 at 18:34

1 Answer 1

0

In my case this made the trick

simply add the following two lines to /etc/apache2/envvars

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

Refer: Can't change Filesystem encoding in Apache → PHP → Python 3 → sys.argv

1
  • 1
    Consider explaining what the info is that is provided when following the external link. In case that link ever goes bad, users visiting this site will still have a way of knowing what you referenced ...
    – Kris
    May 7, 2018 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.