How do you get the encoding of the terminal from within a python script?

Viewed 5751

Let's say you want to start a python script with some parameters like

python myscript some arguments

I understand, that the strings sys.argv[1] and sys.argv[2] will have the encoding specified in the terminal. Is there a way to get this information from within the python script?

My goal is something like this:

terminal_enocding = some_way.to.GET_TERMINAL_ENCODING
some = `sys.argv[1]`.decode(terminal_encoding)
arguments = `sys.argv[2]`.decode(terminal_encoding)
3 Answers

The function locale.getpreferredencoding() also seems to do the job.

It returns the Python encoding string which you can directly use like this:

>>> import locale
>>> s = b'123\n'
>>> enc = locale.getpreferredencoding()
>>> s.decode(enc)
'123\n'
Related