nutools/lib/nulib/python/nulib/encoding.py

101 lines
3.4 KiB
Python

# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
"""Gestion de la langue et de l'encoding par défaut.
"""
__all__ = ('LATIN1', 'LATIN9', 'UTF8', 'MACROMAN',
'normalize_encoding', 'get_encoding_or_default',
)
import os, locale
from locale import setlocale, LC_ALL, getlocale, getdefaultlocale
# Gestion des formes normalisées des encodings
# note: Ces formes sont déclarées normalisées par rapport à ulib, et non par
# rapport à un quelconque organisme de normalisation.
LATIN1 = 'iso-8859-1'
LATIN9 = 'iso-8859-15'
UTF8 = 'utf-8'
MACROMAN = 'MacRoman'
ENCODING_MAP = {'latin-1': LATIN1,
'latin1': LATIN1,
'iso-8859-1': LATIN1,
'iso-88591': LATIN1,
'iso8859-1': LATIN1,
'iso88591': LATIN1,
'latin-9': LATIN9,
'latin9': LATIN9,
'iso-8859-15': LATIN9,
'iso-885915': LATIN9,
'iso8859-15': LATIN9,
'iso885915': LATIN9,
'utf-8': UTF8,
'utf8': UTF8,
'utf': UTF8,
}
def normalize_encoding(encoding):
if encoding is None: return None
lencoding = str(encoding).lower().replace('_', '-')
return ENCODING_MAP.get(lencoding, encoding)
DEFAULT_LANG = 'fr_FR.UTF-8'
LANG_MAP = {LATIN1: 'fr_FR',
LATIN9: 'fr_FR@euro',
UTF8: 'fr_FR.UTF-8',
}
def get_lang_for_encoding(encoding):
return LANG_MAP.get(normalize_encoding(encoding), DEFAULT_LANG)
def __set_locale_noexc(lang):
os.environ['LANG'] = lang
try:
setlocale(LC_ALL, '')
return True
except locale.Error:
return False
__locale_set = False
def __set_locale():
global __locale_set
if not __locale_set:
lang = os.environ.get('LANG', '')
if not lang or normalize_encoding(lang) == UTF8:
os.environ['LANG'] = DEFAULT_LANG
try:
setlocale(LC_ALL, '')
except locale.Error:
print "WARNING: La valeur LANG='%s' n'est pas valide ou n'a pas été reconnue par le systeme." % os.environ['LANG']
langs = (LATIN1, LATIN9, 'C')
if os.environ['LANG'] != DEFAULT_LANG:
print "WARNING: La valeur LANG='%s' sera utilise à la place si possible." % DEFAULT_LANG
if __set_locale_noexc(DEFAULT_LANG):
langs = None
else:
print "WARNING: La valeur LANG='%s' n'a pas pu etre selectionnee." % DEFAULT_LANG
if langs is not None:
for lang in langs:
if __set_locale_noexc(lang):
print "NOTE: la valeur LANG='%s' a ete selectionnee" % lang
break
else:
print "WARNING: La valeur LANG='%s' n'a pas pu etre utilisee." % lang
__locale_set = True
try: from UTOOLS_CONFIG import SET_LOCALE
except ImportError: SET_LOCALE = True
if SET_LOCALE: __set_locale()
def get_encoding_or_default(encoding=None, default_encoding=UTF8):
"""Si encoding est None, essayer de déterminer l'encoding par défaut avec
getlocale(), getdefaultlocale() puis default_encoding.
"""
if encoding is None: _, encoding = getlocale()
if encoding is None: _, encoding = getdefaultlocale()
if encoding is None: encoding = default_encoding
return normalize_encoding(encoding)