[英]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
将为您提供标准输入的编码。
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.