简体   繁体   English

如何从 python 脚本中获取终端的编码?

[英]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 脚本,比如

python myscript some arguments

I understand, that the strings sys.argv[1] and sys.argv[2] will have the encoding specified in the terminal.我知道,字符串sys.argv[1]sys.argv[2]将在终端中指定编码。 Is there a way to get this information from within the python script?有没有办法从 python 脚本中获取这些信息?

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.stdout.encoding会给你标准输出的编码。 sys.stdin.encoding will give you the encdoing for standard input. sys.stdin.encoding将为您提供标准输入的编码。

You can call locale.getdefaultlocale() and use the second part of the tuple.您可以调用locale.getdefaultlocale()并使用元组的第二部分。

See more here (Fedora wiki entry explaining the why's and how's of the default encoding in Python) 在此处查看更多信息(Fedora wiki 条目解释了 Python 中默认编码的原因和方式)

The function locale.getpreferredencoding() also seems to do the job.函数locale.getpreferredencoding()似乎也可以完成这项工作。

It returns the Python encoding string which you can directly use like this:它返回 Python 编码字符串,您可以像这样直接使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM