Skip to content

Instantly share code, notes, and snippets.

@minrk
Created May 12, 2011 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/967940 to your computer and use it in GitHub Desktop.
Save minrk/967940 to your computer and use it in GitHub Desktop.
kv_pattern = re.compile(r'\w+\.[\w\.]+\w\=.+')
macro_pattern = re.compile(r'\-\-\w[\w\-]+')
class KeyValueConfigLoader(CommandLineConfigLoader):
"""A config loader that loads key value pairs from the command line.
This allows command line options to be gives in the following form::
ipython Global.profile="foo" InteractiveShell.autocall=False
"""
def __init__(self, argv=None, shortnames=None, macros=None):
"""Create a key value pair config loader.
Parameters
----------
argv : list
A list that has the form of sys.argv[1:] which has unicode
elements of the form u"key=value". If this is None (default),
then sys.argv[1:] will be used.
shortnames : dict
A dict of aliases for configurable traits.
Keys are the short aliases, Values are the resolved trait.
Of the form: `{'shortname' : 'Configurable.trait'}`
macros : dict
A dict of macros, keyed by the name of the macro, with
Configurables (or dicts) for values.
Returns
-------
config : Config
The resulting Config object.
Examples
--------
>>> from IPython.config.loader import KeyValueConfigLoader
>>> cl = KeyValueConfigLoader()
>>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
{'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
"""
if argv is None:
argv = sys.argv[1:]
self.argv = argv
self.shortnames = shortnames or {}
self.macros = macros or {}
def load_config(self, argv=None, shortnames=None, macros=None):
"""Parse the configuration and generate the Config object.
Parameters
----------
argv : list, optional
A list that has the form of sys.argv[1:] which has unicode
elements of the form u"key=value". If this is None (default),
then self.argv will be used.
shortnames : dict
A dict of aliases for configurable traits.
Keys are the short aliases, Values are the resolved trait.
Of the form: `{'shortname' : 'Configurable.trait'}`
macros : dict
A dict of macros, keyed by the name of the macro, with
Configurables (or dicts) for values.
"""
from IPython.config.configurable import Configurable
self.clear()
if argv is None:
argv = self.argv
if shortnames is None:
shortnames = self.shortnames
if macros is None:
macros = self.macros
for item in argv:
if kv_pattern.match(item):
lhs,rhs = item.split('=',1)
# Substitute longnames for shortnames.
if lhs in shortnames:
lhs = shortnames[lhs]
exec_str = 'self.config.' + lhs + '=' + rhs
try:
# Try to see if regular Python syntax will work. This
# won't handle strings as the quote marks are removed
# by the system shell.
exec exec_str in locals(), globals()
except (NameError, SyntaxError):
# This case happens if the rhs is a string but without
# the quote marks. We add the quote marks and see if
# it succeeds. If it still fails, we let it raise.
exec_str = 'self.config.' + lhs + '="' + rhs + '"'
exec exec_str in locals(), globals()
elif macro_pattern.match(item):
# trim leading '--'
m = item[2:]
if m in macros:
# update self.config with Config:
self.config.update(macros[m])
else:
raise ValueError("Invalid argument: %r"%item)
else:
raise ValueError("Invalid argument: %r"%item)
return self.config
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment