locale getlocale returns None on OSX

Ned Deily nad at acm.org
Wed Mar 12 16:43:44 EDT 2014


In article 
<1394626979.46880.YahooMailBasic at web163806.mail.gq1.yahoo.com>,
 Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> locale.getlocale() sometimes returns (None, None) under OSX (Python 2, not 
> sure about Python 3, but I think so). The problem is outlined here:
> http://stackoverflow.com/questions/1629699/locale-getlocale-problems-on-osx

Python's locale uses the plaform's locale implementation and POSIX 
locale is an old and somewhat weird animal.  Make sure you thoroughly 
read the description of the locale module, in particular, the caveats 
section:

http://docs.python.org/2/library/locale.html#background-details-hints-tip
s-and-caveats

The first gotcha is that you need to explicitly call 
locale.setlocale("LC_ALL,"") to get the preferred locale environment, as 
either specified by the user, by LANG or other LC_* environment 
variables, or the platform defaults.  In general, OS X does not provide 
a default for your process.  However, various environments do.  The OS X 
Terminal.app has profile settings (Preferences -> Settings -> (Profile 
name) -> Advanced) to specific a character encoding and a checkbox to 
"Set locale environment variables on startup".  With that set properly, 
programs run under Terminal.app will see LANG set.  The user can also 
set an explicit LANG value in a shell profile, like .profile or .bashrc, 
but those only apply when a shell is being used.  Depending on which 
profile it is set in, that might not work under all conditions, like 
under "sudo" or in an "ssh" session.  Setting an env variable in a shell 
profile would also not apply to an double-clickable app bundle since no 
shell is involved in launching it; it is possible to set environment 
variables in the app's Info.plist, though.
 
> What is the cause of this? Is it limited to just Darwin systes? Does the 
> 'horrible hack' solution on OS have any drawbacks? I like it better because 
> it is not needed to set the LC_ALL environment variable prior to starting the 
> Python program.

As the caveats section points out, setting locale env vars may have 
unwanted side effects on other parts of the process it is running in or 
creates.  So, if you are using it in a standalone program, it may be OK.  
If you are using it a module intended to be used by other programs, you 
probably shouldn't be changing something that could break other parts of 
the calling program.

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list