##// END OF EJS Templates
Semi-final Application and minor work on traitlets.
Semi-final Application and minor work on traitlets.

File last commit:

r2200:9506581e
r2200:9506581e
Show More
loader.py
200 lines | 6.1 KiB | text/x-python | PythonLexer
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 #!/usr/bin/env python
# encoding: utf-8
"""A factory for creating configuration objects.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2009 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 import sys
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 from IPython.external import argparse
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 from IPython.utils.ipstruct import Struct
Brian Granger
Semi-final Application and minor work on traitlets.
r2200 from IPython.utils.genutils import filefind
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
class ConfigLoaderError(Exception):
pass
class ConfigLoader(object):
"""A object for loading configurations from just about anywhere.
The resulting configuration is packaged as a :class:`Struct`.
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Notes
-----
A :class:`ConfigLoader` does one thing: load a config from a source
(file, command line arguments) and returns the data as a :class:`Struct`.
There are lots of things that :class:`ConfigLoader` does not do. It does
not implement complex logic for finding config files. It does not handle
default values or merge multiple configs. These things need to be
handled elsewhere.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """
def __init__(self):
"""A base class for config loaders.
Examples
--------
>>> cl = ConfigLoader()
>>> config = cl.load_config()
>>> config
{}
"""
self.clear()
def clear(self):
self.config = Struct()
def load_config(self):
"""Load a config from somewhere, return a Struct.
Usually, this will cause self.config to be set and then returned.
"""
return self.config
class FileConfigLoader(ConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 """A base class for file based configurations.
As we add more file based config loaders, the common logic should go
here.
"""
pass
class PyFileConfigLoader(FileConfigLoader):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """A config loader for pure python files.
This calls execfile on a plain python file and looks for attributes
that are all caps. These attribute are added to the config Struct.
"""
Brian Granger
Semi-final Application and minor work on traitlets.
r2200 def __init__(self, filename, path=None):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """Build a config loader for a filename and path.
Parameters
----------
filename : str
The file name of the config file.
path : str, list, tuple
The path to search for the config file on, or a sequence of
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 paths to try in order.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 """
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 super(PyFileConfigLoader, self).__init__()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.filename = filename
self.path = path
self.full_filename = ''
self.data = None
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def load_config(self):
"""Load the config from a file and return it as a Struct."""
self._find_file()
self._read_file_as_dict()
self._convert_to_struct()
return self.config
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _find_file(self):
"""Try to find the file by searching the paths."""
Brian Granger
Semi-final Application and minor work on traitlets.
r2200 self.full_filename = filefind(self.filename, self.path)
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
def _read_file_as_dict(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.data = {}
execfile(self.full_filename, self.data)
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _convert_to_struct(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 if self.data is None:
ConfigLoaderError('self.data does not exist')
for k, v in self.data.iteritems():
if k == k.upper():
self.config[k] = v
class CommandLineConfigLoader(ConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 """A config loader for command line arguments.
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 As we add more command line based loaders, the common logic should go
here.
"""
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 class NoDefault(object): pass
NoDefault = NoDefault()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
class ArgParseConfigLoader(CommandLineConfigLoader):
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 # arguments = [(('-f','--file'),dict(type=str,dest='file'))]
Brian Granger
Minor changes to a few files to reflect design discussion.
r2198 arguments = ()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
def __init__(self, *args, **kw):
"""Create a config loader for use with argparse.
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 The args and kwargs arguments here are passed onto the constructor
of :class:`argparse.ArgumentParser`.
"""
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 super(CommandLineConfigLoader, self).__init__()
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.args = args
self.kw = kw
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def load_config(self, args=None):
"""Parse command line arguments and return as a Struct."""
self._create_parser()
self._parse_args(args)
self._convert_to_struct()
return self.config
def _create_parser(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 self._add_arguments()
Brian Granger
Semi-final Application and minor work on traitlets.
r2200 self._add_other_arguments()
def _add_other_arguments():
pass
Brian Granger
First prototype of component, traitlets and a config loader.
r2157
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _add_arguments(self):
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 for argument in self.arguments:
Brian Granger
Added simple tests for IPython.config.loader.
r2186 if not argument[1].has_key('default'):
argument[1]['default'] = NoDefault
Brian Granger
First prototype of component, traitlets and a config loader.
r2157 self.parser.add_argument(*argument[0],**argument[1])
Brian Granger
Working version of the new config loaders for .py files and argparse.
r2185 def _parse_args(self, args=None):
"""self.parser->self.parsed_data"""
if args is None:
self.parsed_data = self.parser.parse_args()
else:
self.parsed_data = self.parser.parse_args(args)
def _convert_to_struct(self):
"""self.parsed_data->self.config"""
self.config = Struct()
for k, v in vars(self.parsed_data).items():
if v is not NoDefault:
setattr(self.config, k, v)
Brian Granger
Semi-final Application and minor work on traitlets.
r2200 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
def _add_other_arguments(self):
self.parser.add_argument('--ipythondir',dest='IPYTHONDIR',type=str,
help='set to override default location of IPYTHONDIR',
default=NoDefault)
self.parser.add_argument('-p','--p',dest='PROFILE_NAME',type=str,
help='the string name of the ipython profile to be used',
default=None)
self.parser.add_argument('--debug',dest="DEBUG",action='store_true',
help='debug the application startup process',
default=NoDefault)