获取系统语言最简单的方法是调用locale,例如
import locale
print(locale.getdefaultlocale())
但是用pyinstaller打包成app后,该函数始终返回None。在调试窗口运行一切正常。用另一种方法
import os
print(os.environ.get("LC_CTYPE"))
亦是一模一样的情况,似乎是打包到app后,运行时连同系统环境变量一起被屏蔽,百思不得解。
仔细查看打包后仅能获取到的寥寥几个系统环境变量,有个
'__CF_USER_TEXT_ENCODING'= 0x1F5:0x19:0x34
似乎与系统语言有些关系。搜索一番后,果然:
CFUserTextEncoding containing a string of the form M:0:N, where each of the three numbers is usually given in hexadecimal, for example as 0x1F5:0x0:0x2, which specifies that user number 501 (hex 1F5) uses encoding number 2. Normally, in the .CFUserTextEncoding file the user number is left as 0x0 for the system to convert into that user’s UID.
This doesn’t set the language or locale for that user, but the encoding used by CFString, and the full list of supported encodings is provided in Apple’s reference documentation for CFString.
顺藤摸瓜找到apple的官方说明,很清楚的标明
case macChineseSimp = 25
正是第二组值0x19。这下就能解决了:
import os
def get_sys_encodeing() -> str:
mac_external_string_encodings: dict = {0: "English",
1: "Japanese",
2: "ChineseTrad",
3: "Korean",
25: "ChineseSimp"
}
try:
hex_encoding = os.environ.get('__CF_USER_TEXT_ENCODING').split(":")[1]
lang_index = int(hex_encoding, base=16)
except:
pass
return mac_external_string_encodings.get(lang_index, "Not Find")