开发者

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

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 th开发者_如何学Ce 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)


sys.stdout.encoding will give you the encoding of standard output. sys.stdin.encoding will give you the encdoing for standard input.


You can call locale.getdefaultlocale() and use the second part of the tuple.

See more here (Fedora wiki entry explaining the why's and how's of the default encoding in Python)


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜