From c3422e8103cb662015e84f5a5ffc29b4333aa062 Mon Sep 17 00:00:00 2001 From: Wolfgang Doll Date: Fri, 23 Jun 2017 12:03:23 +0200 Subject: [PATCH] Introduce PyInstaller support. Fixes #500 Add a get_base_dir function that works in the context of PyInstaller, where the __file__ system variable is not available. --- babel/core.py | 2 +- babel/localedata.py | 12 +++++++++++- tests/test_localedata.py | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/babel/core.py b/babel/core.py index 5140f49d..df03b24a 100644 --- a/babel/core.py +++ b/babel/core.py @@ -68,7 +68,7 @@ def get_global(key): """ global _global_data if _global_data is None: - dirname = os.path.join(os.path.dirname(__file__)) + dirname = localedata.get_base_dir() filename = os.path.join(dirname, 'global.dat') if not os.path.isfile(filename): _raise_no_data_error() diff --git a/babel/localedata.py b/babel/localedata.py index 9e272a27..46582212 100644 --- a/babel/localedata.py +++ b/babel/localedata.py @@ -16,13 +16,23 @@ import os import threading from collections import MutableMapping from itertools import chain +import sys from babel._compat import pickle +def get_base_dir(): + if getattr(sys, 'frozen', False): + # we are running in a |PyInstaller| bundle + basedir = sys._MEIPASS + else: + # we are running in a normal Python environment + basedir = os.path.dirname(__file__) + return basedir + _cache = {} _cache_lock = threading.RLock() -_dirname = os.path.join(os.path.dirname(__file__), 'locale-data') +_dirname = os.path.join(get_base_dir(), 'locale-data') def normalize_locale(name): diff --git a/tests/test_localedata.py b/tests/test_localedata.py index 6a41ac2a..a23987f2 100644 --- a/tests/test_localedata.py +++ b/tests/test_localedata.py @@ -14,6 +14,7 @@ import unittest import random from operator import methodcaller +import sys from babel import localedata @@ -94,3 +95,16 @@ def test_mixedcased_locale(): locale_id = ''.join([ methodcaller(random.choice(['lower', 'upper']))(c) for c in l]) assert localedata.exists(locale_id) + +def test_pi_support_frozen(): + sys._MEIPASS, sys.frozen = 'testdir', True + try: + assert localedata.get_base_dir() == 'testdir' + finally: + del sys._MEIPASS + del sys.frozen + + +def test_pi_support_not_frozen(): + assert not getattr(sys, 'frozen', False) + assert localedata.get_base_dir().endswith('babel') -- 2.47.2