Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix macos getlocale is None error #478

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

adntian
Copy link

@adntian adntian commented Dec 30, 2024

Fix: Handle None error in locale detection for language settings

  • Added a check to ensure locale.getlocale()[0] is not None before calling .lower().
  • Prevents potential AttributeError when locale information is missing or unset.
  • Defaulted to 'en' if the locale language is unavailable.

修正在macos上,getlocal的输出可能是(None, 'UTF-8'),此时会报AttributeError: 'NoneType' object has no attribute 'lower'错误(Macbook M1 Pro)

Fix: Handle None error in locale detection for language settings

- Added a check to ensure `locale.getlocale()[0]` is not None before calling `.lower()`.
- Prevents potential `AttributeError` when locale information is missing or unset.
- Defaulted to 'en' if the locale language is unavailable.
@g1879
Copy link
Owner

g1879 commented Dec 30, 2024

谢谢,但这只是避免了报错,没有正确识别MAC系统使用的语言。我没有MAC系统,可以帮忙看看怎么获取MAC系统语言吗?

@adntian
Copy link
Author

adntian commented Dec 31, 2024

使用locale相关的方法,获取到的都是(None, 'UTF-8')
直接执行程序的时候,会报AttributeError: 'NoneType' object has no attribute 'lower'错误,修改源码才可以运行
要换其它,让gpt帮我看了一下

推荐包:pyobjc 直接调用 macOS API,是最原生的方法;babel 和 pycountry 提供语言名的国际化支持。

from Foundation import NSUserDefaults

def get_system_language_with_pyobjc():
    defaults = NSUserDefaults.standardUserDefaults()
    languages = defaults.objectForKey_("AppleLanguages")
    if languages:
        return languages[0]
    return "Unable to determine language"

language = get_system_language_with_pyobjc()
print("当前系统语言:", language)

在我电脑上执行的结果是

当前系统语言: zh-Hans-CN

我的系统首选语言切换为英语后,执行结果是

当前系统语言: en-CN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants