Skip to content

Instantly share code, notes, and snippets.

@AlmightyOatmeal
Last active May 8, 2018 23:03
Show Gist options
  • Save AlmightyOatmeal/057fdd5174714b6d75ce3c0948c4d7d9 to your computer and use it in GitHub Desktop.
Save AlmightyOatmeal/057fdd5174714b6d75ce3c0948c4d7d9 to your computer and use it in GitHub Desktop.
Fun with Python and locale! Works on Python 2.7.x.
import locale
import logging
import os
logger = logging.getLogger(os.path.splitext(os.path.basename(__file__))[0])
def set_locale(desired_locale=('en_US', 'UTF-8')):
"""Set the local for proper formatting.
.. note::
* `locale.setlocale() <https://docs.python.org/2/library/locale.html#locale.setlocale>`_
:param desired_locale: (optional) Tuple of the locale language and character-set. The default will be
"en_US.UTF-8". (default: ('en_US', 'UTF-8'))
:type desired_locale: tuple
:return: True if the setting was successful otherwise return False.
:rtype: bool
"""
logging.getLogger('set_locale')
current_locale = locale.getlocale()
if set(current_locale) == set(desired_locale):
logger.info('Desired locale ("LC_ALL") is already "{}", nothing to do.'.format('.'.join(desired_locale)))
return True
try:
logger.info('Setting locale ("LC_ALL") to "{}".'.format('.'.join(desired_locale)))
locale.setlocale(locale.LC_ALL, desired_locale)
return True
except locale.Error as err:
logger.exception(err)
return False
def set_console_encoding(encoding='utf-8'):
"""Set console encoding.
:param encoding: (optional) Encoding.
(default: 'utf-8')
:type encoding: str, unicode, basestring
:return: True if successful and False if not.
:rtype: bool
"""
try:
if globals().get('sys') is None:
import sys
# First, reload the sys module.
# For Python 3.0 - 3.3: use imp
# For Python >=3.4: use importlib
if sys.version_info.major == 2:
reload(sys)
elif sys.version_info.major == 3:
if 0 <= sys.version_info.minor <= 3:
if globals().get('imp') is None:
import imp
imp.reload(sys)
elif sys.version_info.minor >= 4:
if globals().get('importlib') is None:
import importlib
importlib.reload(sys)
sys.setdefaultencoding(encoding)
logger.info('Set console encoding to "{}".'.format(encoding))
return True
except Exception as err:
logger.exception(err)
return False
def convert_number_to_human_readable_string(data, fmt=None, grouping=True, **kwargs):
"""Convert number to human-readable string based on locale. Additional kwargs passed to locale.format().
:param data: Some kind of number.
:type data: int, float, long
:param fmt: (optional) Number format. (default: None)
:param grouping: (optional) Take grouping into account. (default: True)
:type grouping: bool
:return: Human-readable string.
:rtype: basestring, str, unicode
"""
if fmt is not None:
return locale.format(fmt, data, grouping=grouping, **kwargs)
if isinstance(data, (int, long)):
return locale.format('%d', data, grouping=grouping, **kwargs)
if isinstance(data, float):
return locale.format('%f', data, grouping=grouping, **kwargs)
return data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment