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

怎甘沉沦 提交于 2019-12-18 19:10:17

问题


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)

回答1:


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




回答2:


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)



来源:https://stackoverflow.com/questions/6396659/how-do-you-get-the-encoding-of-the-terminal-from-within-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!