Commits

Chris Mutel committed 44513fe

10.2. Color is back on Windows.

Comments (0)

Files changed (10)

bw2data/__init__.py

 # -*- coding: utf-8 -*
-__version__ = (0, 10, 1)
+__version__ = (0, 10, 2)
 
 from _config import config
 from meta import databases, methods, mapping, reset_meta, geomapping, \

bw2data/_config.py

 import warnings
 
 
+def _ran_from_ipython():
+    try:
+        __IPYTHON__
+        return True
+    except NameError:
+        return False
+
+
 class Config(object):
     """A singleton that store configuration settings. Default data directory is ``brightway`` in the user's home directory, and is stored as ``config.dir``. Other configuration settings can also be assigned as needed.
 
     version = 0.1
     basic_directories = ("processed", "intermediate", "backups", "logs")
     _windows = platform.system() == "Windows"
+    _ipython = _ran_from_ipython()
 
     # TODO: Create directory if needed (and basic dirs)
 

bw2data/bin/bw2-uptodate.py

   --version     Show version.
 
 """
+from __future__ import print_function
 from docopt import docopt
 import sys
 import warnings
     warnings.simplefilter("ignore")
     from bw2data import config
     from bw2data.upgrades import *
-    from bw2data.utils import Fore
-
+from bw2data.colors import Fore, init, deinit
 
 EXPLANATIONS = {
     "stats_array reformat": Fore.GREEN + "\nstats_array reformat:" + Fore.RESET + """
     Brightway2 tries to normalize units so that they are consistent from machine to machine, and person to person. For example, ``m2a`` is changed to ``square meter-year``. This update adds more data normalizations, and needs to updates links across databases.""",
 }
 
+
 class Updater(object):
     def needed(self):
         try:
     def list(self):
         updates_needed = self.needed()
         if not updates_needed:
-            print Fore.GREEN + "\n*** Brightway2 is up to date! ***\n" + \
-                Fore.RESET
+            print(Fore.GREEN + "\n*** Brightway2 is up to date! ***\n")
         else:
-            print Fore.RED + "\n*** Updates found ***" + Fore.RESET
+            print(Fore.RED + "\n*** Updates found ***")
             for update in updates_needed:
-                print EXPLANATIONS[update]
-            print Fore.RED + "\n*** Action needed ***" + Fore.RESET + \
-                "\nPlease run " + Fore.BLUE + "bw2-uptodate.py\n" + Fore.RESET
+                print(EXPLANATIONS[update])
+            print(Fore.RED + "\n*** Action needed ***" + Fore.RESET + \
+                "\nPlease run " + Fore.BLUE + "bw2-uptodate.py\n")
 
     def update(self, confirm=True):
         updates_needed = self.needed()
 
         if updates_needed:
-            print Fore.GREEN + "\nThe following upgrades will be applied:\n"
+            print(Fore.GREEN + "\nThe following upgrades will be applied:\n")
             for update in updates_needed:
-                print EXPLANATIONS[update]
+                print(EXPLANATIONS[update])
             if confirm:
                 confirmation = raw_input("\nType '" + Fore.MAGENTA  + "y" + \
                     Fore.RESET + "'to confirm, " + Fore.RED + "anything else" + \
                     Fore.RESET + " to cancel: "
                 )
                 if confirmation.strip() != 'y':
-                    print Fore.MAGENTA + "\n*** Upgrade canceled ***\n" + \
-                        Fore.RESET
+                    print(Fore.MAGENTA + "\n*** Upgrade canceled ***\n")
                     sys.exit(0)
 
             if "stats_array reformat" in updates_needed:
                 config.p["upgrades"]["0.10 units restandardization"] = True
             config.save_preferences()
         else:
-            print Fore.GREEN + "\n*** Brightway2 is up to date! ***\n" + \
-                Fore.RESET
+            print(Fore.GREEN + "\n*** Brightway2 is up to date! ***\n")
 
 
 if __name__ == "__main__":
-    config.create_basic_directories()
-    args = docopt(__doc__, version='Brightway2 up to date 0.1')
-    updater = Updater()
-    if args['--list']:
-        updater.list()
-    else:
-        updater.update()
+    try:
+        init(autoreset=True)
+        config.create_basic_directories()
+        args = docopt(__doc__, version='Brightway2 up to date 0.1')
+        updater = Updater()
+        if args['--list']:
+            updater.list()
+        else:
+            updater.update()
+    except:
+        deinit()
+        raise
+    finally:
+        deinit()

bw2data/colors.py

+from . import config
+from contextlib import contextmanager
+
+
+if not config._ipython:
+    from colorama import Fore, init, deinit
+
+    # ASCII color codes
+    # class Fore(object):
+    #     BLACK = '\x1b[30m'
+    #     CYAN = '\x1b[36m'
+    #     MAGENTA = '\x1b[35m'
+    #     RESET = '\x1b[39m'
+    #     YELLOW = '\x1b[33m'
+    #     BLUE = '\x1b[34m'
+    #     GREEN = '\x1b[32m'
+    #     RED = '\x1b[31m'
+    #     WHITE = '\x1b[37m'
+else:
+    # IPython seems to screw up colorama, maybe by not printing to stdout
+    # Can globally disable for windows as well...
+    # See also http://stackoverflow.com/questions/9848889/colorama-for-python-not-returning-colored-print-lines-on-windows
+    class _Fore(object):
+        def __getattr__(self, *args, **kwargs):
+            return ""
+    Fore = _Fore()
+
+    def init(*args, **kwargs):
+        return
+
+    def deinit(*args, **kwargs):
+        return
+
+@contextmanager
+def safe_colorama():
+    init()
+    try:
+        yield
+    finally:
+        deinit()

bw2data/database.py

 import datetime
 import numpy as np
 import os
+import random
 import warnings
 try:
     import cPickle as pickle
             pickle.dump(self.load(), f, protocol=pickle.HIGHEST_PROTOCOL)
         return filepath
 
+    def random(self):
+        """Return a random activity key.
+
+        Returns a random activity key, or ``None`` (and issues a warning) if the current database is empty."""
+        keys = self.load().keys()
+        if not keys:
+            warnings.warn("This database is empty")
+            return None
+        else:
+            return random.choice(keys)
+
     def revert(self, version):
         """Return data to a previous state.
 

bw2data/upgrades.py

 # -*- coding: utf-8 -*-
 from . import Database, databases, Method, methods, config
-from .utils import activity_hash, Fore
+from .colors import Fore, safe_colorama
 from .units import normalize_units
+from .utils import activity_hash
 import numpy as np
 import progressbar
 import sys
 import warnings
 
+
 STATS_ARRAY_WARNING = "\n\nIt looks like you need to upgrade to the ``" + \
     Fore.GREEN + "stats_arrays" + Fore.RESET + \
     "`` package. This is a new statistical toolkit that replaces the deprecated ``" \
     try:
         import stats_arrays
     except ImportError:
-        warnings.warn(STATS_ARRAY_WARNING)
-        try:
+        warnings.warn(safe_colorama(STATS_ARRAY_WARNING))
+        if config._ipython:
             # ipython won't let us leave the shell...
-            __IPYTHON__
-        except:
+            print "Please exit the IPython shell now"
+            return
+        else:
             sys.exit(0)
     updates = []
     if not databases.list:
     if not config.p['upgrades'].get('0.10 units restandardization', False):
         updates.append('0.10 units restandardization')
     if updates:
-        warnings.warn(UPTODATE_WARNING)
+        warnings.warn(safe_colorama(UPTODATE_WARNING))
     return updates
 
 
 
 DOWNLOAD_URL = "http://brightwaylca.org/data/"
 
-if config._windows:
-    # Colorama no workie, grumble grumble
-    # See http://stackoverflow.com/questions/9848889/colorama-for-python-not-returning-colored-print-lines-on-windows
-    class _Fore(object):
-        def __getattr__(self, arg):
-            return ""
-    Fore = _Fore()
-else:
-    class Fore(object):
-        BLACK = '\x1b[30m'
-        CYAN = '\x1b[36m'
-        MAGENTA = '\x1b[35m'
-        RESET = '\x1b[39m'
-        YELLOW = '\x1b[33m'
-        BLUE = '\x1b[34m'
-        GREEN = '\x1b[32m'
-        RED = '\x1b[31m'
-        WHITE = '\x1b[37m'
-
 
 def natural_sort(l):
     """Sort the given list in the way that humans expect"""
 # The short X.Y version.
 version = '0.10'
 # The full version, including alpha/beta/rc tags.
-release = '0.10.1'
+release = '0.10.2'
 
 # The language for content autogenerated by Sphinx. Refer to documentation
 # for a list of supported languages.
 voluptuous
 brightway2>=0.10
 stats_arrays
+colorama
 
 setup(
     name='bw2data',
-    version="0.10.1",
+    version="0.10.2",
     packages=packages,
     author="Chris Mutel",
     author_email="cmutel@gmail.com",
     license=open('LICENSE.txt').read(),
     install_requires=[
         "brightway2",
+        "colorama",
         "docopt",
         "lxml",
         "numpy",
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.