Skip to content

how to get local on non-posix os like windows and apple #820

@ikus060

Description

@ikus060

Does Babel allow to detect the proper locale on non POSIX operating system. Had a look at the code and can't figure out if Babel is POSIX only.

Working on a desktop application, the translation file does not get loaded according to the user preferred languages.

Activity

akx

akx commented on Jan 26, 2022

@akx
Member

The default_locale() function definitely only looks as the posixesque environment variable keys.

macOS is a POSIX OS, but it might well be that the environment variables don't get set according to the user's locale preferences.

A PR to enhance default_locale() for cross-platform use is welcome.

jeanas

jeanas commented on Oct 16, 2023

@jeanas
Contributor

Can't you use locale.getlocale? (I don't have a Windows machine to check what it does there, but I think it works.)

akx

akx commented on May 7, 2024

@akx
Member

Closing as stale.

ikus060

ikus060 commented on May 21, 2024

@ikus060
Author

I came up with something like this in my application to load the proper language file for Windows and MacOS.

__all__ = ['_', 'gettext', 'ngettext']

import gettext as _gt
import locale
import os
import sys

import pkg_resources

# On MacOS, we need to get the language using native API. Because the LANG
# environment variable is not pass to the application bundle.
languages = None
if sys.platform == 'darwin':
    try:
        import Foundation

        sud = Foundation.NSUserDefaults.standardUserDefaults()  # @UndefinedVariable
        languages = [str(sud.stringForKey_('AppleLocale'))]
    except ImportError:
        pass
elif sys.platform == 'win32':
    try:
        import ctypes

        windll = ctypes.windll.kernel32
        languages = [locale.windows_locale[windll.GetUserDefaultUILanguage()]]
        # For testing we support environment variable too
        if os.environ.get('LANGUAGE', None):
            languages.insert(0, os.environ.get('LANGUAGE'))
    except ImportError:
        pass

# Load translations
localedir = pkg_resources.resource_filename(__name__, 'locales')
try:
    t = _gt.translation('messages', localedir, languages=languages)
except OSError:
    t = _gt.NullTranslations()

_ = gettext = t.gettext
ngettext = t.ngettext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @akx@ikus060@jeanas

        Issue actions