Python在MacOS下调用locale.getdefaultlocale()返回值为None的另类解决

获取系统语言最简单的方法是调用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")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值