##// END OF EJS Templates
Created config.application and updated Configurable.
Brian Granger -
Show More
@@ -0,0 +1,108 b''
1 # encoding: utf-8
2 """
3 A base class for a configurable application.
4
5 Authors:
6
7 * Brian Granger
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2011 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
16
17 #-----------------------------------------------------------------------------
18 # Imports
19 #-----------------------------------------------------------------------------
20
21 from copy import deepcopy
22 import sys
23
24 from IPython.config.configurable import Configurable
25 from IPython.utils.traitlets import (
26 Unicode, List
27 )
28 from IPython.config.loader import (
29 KeyValueConfigLoader, PyFileConfigLoader
30 )
31
32 #-----------------------------------------------------------------------------
33 # Application class
34 #-----------------------------------------------------------------------------
35
36
37 class Application(Configurable):
38
39 # The name of the application, will usually match the name of the command
40 # line application
41 app_name = Unicode(u'application')
42
43 # The description of the application that is printed at the beginning
44 # of the help.
45 description = Unicode(u'This is an application.')
46
47 # A sequence of Configurable subclasses whose config=True attributes will
48 # be exposed at the command line (shortnames and help).
49 classes = List([])
50
51 # The version string of this application.
52 version = Unicode(u'0.0')
53
54 def __init__(self, **kwargs):
55 Configurable.__init__(self, **kwargs)
56 # Add my class to self.classes so my attributes appear in command line
57 # options.
58 self.classes.insert(0, self.__class__)
59
60 def print_help(self):
61 """Print the help for each Configurable class in self.classes."""
62 for cls in self.classes:
63 cls.class_print_help()
64 print
65
66 def print_description(self):
67 """Print the application description."""
68 print self.description
69 print
70
71 def print_version(self):
72 """Print the version string."""
73 print self.version
74
75 def update_config(self, config):
76 # Save a copy of the current config.
77 newconfig = deepcopy(self.config)
78 # Merge the new config into the current one.
79 newconfig._merge(config)
80 # Save the combined config as self.config, which triggers the traits
81 # events.
82 self.config = config
83
84 def parse_command_line(self, argv=None):
85 """Parse the command line arguments."""
86 if argv is None:
87 argv = sys.argv[1:]
88
89 if '-h' in argv or '--h' in argv:
90 self.print_description()
91 self.print_help()
92 sys.exit(1)
93
94 if '--version' in argv:
95 self.print_version()
96 sys.exit(1)
97
98 loader = KeyValueConfigLoader(argv=argv, classes=self.classes)
99 config = loader.load_config()
100 self.update_config(config)
101
102 def load_config_file(self, filename, path=None):
103 """Load a .py based config file by filename and path."""
104 # TODO: this raises IOError if filename does not exist.
105 loader = PyFileConfigLoader(filename, path=path)
106 config = loader.load_config()
107 self.update_config(config)
108
@@ -22,9 +22,7 b' Authors:'
22
22
23 from copy import deepcopy
23 from copy import deepcopy
24 import datetime
24 import datetime
25 from weakref import WeakValueDictionary
26
25
27 from IPython.utils.importstring import import_item
28 from loader import Config
26 from loader import Config
29 from IPython.utils.traitlets import HasTraits, Instance
27 from IPython.utils.traitlets import HasTraits, Instance
30 from IPython.utils.text import indent
28 from IPython.utils.text import indent
@@ -152,13 +150,18 b' class Configurable(HasTraits):'
152
150
153 @classmethod
151 @classmethod
154 def class_get_help(cls):
152 def class_get_help(cls):
153 """Get the help string for this class in ReST format."""
155 cls_traits = cls.class_traits(config=True)
154 cls_traits = cls.class_traits(config=True)
156 final_help = []
155 final_help = []
157 final_help.append('%s options' % cls.__name__)
156 final_help.append(u'%s options' % cls.__name__)
158 final_help.append(len(final_help[0])*'-')
157 final_help.append(len(final_help[0])*u'-')
159 for k, v in cls_traits.items():
158 for k, v in cls_traits.items():
160 help = v.get_metadata('help')
159 help = v.get_metadata('help')
161 final_help.append(k + " : " + v.__class__.__name__)
160 shortname = v.get_metadata('shortname')
161 header = "%s.%s : %s" % (cls.__name__, k, v.__class__.__name__)
162 if shortname is not None:
163 header += " (shortname=" + shortname + ")"
164 final_help.append(header)
162 if help is not None:
165 if help is not None:
163 final_help.append(indent(help))
166 final_help.append(indent(help))
164 return '\n'.join(final_help)
167 return '\n'.join(final_help)
@@ -1,10 +1,10 b''
1 import sys
1 import sys
2
2
3 from IPython.config.configurable import Configurable
3 from IPython.config.configurable import Configurable
4 from IPython.config.application import Application
4 from IPython.utils.traitlets import (
5 from IPython.utils.traitlets import (
5 Bool, Unicode, Int, Float, List
6 Bool, Unicode, Int, Float, List
6 )
7 )
7 from IPython.config.loader import KeyValueConfigLoader
8
8
9 class Foo(Configurable):
9 class Foo(Configurable):
10
10
@@ -18,35 +18,19 b' class Bar(Configurable):'
18 enabled = Bool(True, config=True, shortname="bar-enabled", help="Enable bar.")
18 enabled = Bool(True, config=True, shortname="bar-enabled", help="Enable bar.")
19
19
20
20
21 class MyApp(Configurable):
21 class MyApp(Application):
22
22
23 app_name = Unicode(u'myapp', config=True, shortname="myapp", help="The app name.")
23 app_name = Unicode(u'myapp')
24 running = Bool(False, config=True, shortname="running", help="Is the app running?")
24 running = Bool(False, config=True, shortname="running", help="Is the app running?")
25 classes = List([Bar, Foo])
25 classes = List([Bar, Foo])
26
26 config_file = Unicode(u'', config=True, shortname="config-file", help="Load this config file")
27 def __init__(self, **kwargs):
28 Configurable.__init__(self, **kwargs)
29 self.classes.insert(0, self.__class__)
30
31 def print_help(self):
32 for cls in self.classes:
33 cls.class_print_help()
34 print
35
36 def parse_command_line(self, argv=None):
37 if argv is None:
38 argv = sys.argv[1:]
39 if '-h' in argv or '--h' in argv:
40 self.print_help()
41 sys.exit(1)
42 loader = KeyValueConfigLoader(argv=argv, classes=self.classes)
43 config = loader.load_config()
44 self.config = config
45
27
46
28
47 def main():
29 def main():
48 app = MyApp()
30 app = MyApp()
49 app.parse_command_line()
31 app.parse_command_line()
32 if app.config_file:
33 app.load_config_file(app.config_file)
50 print "app.config:"
34 print "app.config:"
51 print app.config
35 print app.config
52
36
General Comments 0
You need to be logged in to leave comments. Login now