Back to index

python-cliapp  1.20120630
Public Member Functions | Public Attributes | Properties | Private Member Functions | Private Attributes
cliapp.settings.Settings Class Reference

List of all members.

Public Member Functions

def __init__
def string
def string_list
def choice
def boolean
def bytesize
def integer
def __getitem__
def __setitem__
def __contains__
def __iter__
def keys
def require
def build_parser
def parse_args
def set_from_raw_string
def load_configs
def as_cp
def dump_config

Public Attributes

 version
 progname
 usage
 description
 epilog

Properties

 config_files = property(_get_config_files, _set_config_files)

Private Member Functions

def _add_default_settings
def _add_setting
def _option_names
def _destname
def _default_config_files
def _listconfs
def _get_config_files
def _set_config_files
def _generate_manpage

Private Attributes

 _settingses
 _canonical_names
 _config_files
 _cp
 _arg_synopsis
 _cmd_synopsis

Detailed Description

Settings for a cliapp application.

You probably don't need to create a settings object yourself,
since ``cliapp.Application`` does it for you.

Settings are read from configuration files, and parsed from the
command line. Every setting has a type, name, and help text,
and may have a default value as well.

For example::

    settings.boolean(['verbose', 'v'], 'show what is going on')
    
This would create a new setting, ``verbose``, with a shorter alias
``v``. On the command line, the options ``--verbose`` and
``-v`` would work equally well. There can be any number of aliases. 

The help text is shown if the user uses ``--help`` or
``--generate-manpage``.
You can use the ``metavar`` keyword argument to set the name shown
in the generated option lists; the default name is whatever
``optparse`` decides (i.e., name of option).

Use ``load_configs`` to read configuration files, and
``parse_args`` to parse command line arguments.

The current value of a setting can be accessed by indexing
the settings class::

    settings['verbose']

The list of configuration files for the appliation is stored
in ``config_files``. Add or remove from the list if you wish.
The files need to exist: those that don't are silently ignored.

Definition at line 217 of file settings.py.


Constructor & Destructor Documentation

def cliapp.settings.Settings.__init__ (   self,
  progname,
  version,
  usage = None,
  description = None,
  epilog = None 
)

Definition at line 257 of file settings.py.

00257 
00258                  epilog=None):
00259         self._settingses = dict()
00260         self._canonical_names = list()
00261 
00262         self.version = version
00263         self.progname = progname
00264         self.usage = usage
00265         self.description = description
00266         self.epilog = epilog
00267         
00268         self._add_default_settings()
00269         
00270         self._config_files = None
00271         self._cp = ConfigParser.ConfigParser()


Member Function Documentation

def cliapp.settings.Settings.__contains__ (   self,
  name 
)

Definition at line 362 of file settings.py.

00362 
00363     def __contains__(self, name):
00364         return name in self._settingses
        
def cliapp.settings.Settings.__getitem__ (   self,
  name 
)

Definition at line 356 of file settings.py.

00356 
00357     def __getitem__(self, name):
00358         return self._settingses[name].value

Iterate over canonical settings names.

Definition at line 365 of file settings.py.

00365 
00366     def __iter__(self):
00367         '''Iterate over canonical settings names.'''
00368         for name in self._canonical_names:
00369             yield name

def cliapp.settings.Settings.__setitem__ (   self,
  name,
  value 
)

Definition at line 359 of file settings.py.

00359 
00360     def __setitem__(self, name, value):
00361         self._settingses[name].value = value

Definition at line 272 of file settings.py.

00272 
00273     def _add_default_settings(self):
00274         self.string(['output'], 
00275                     'write output to FILE, instead of standard output',
00276                     metavar='FILE')
00277 
00278         self.string(['log'], 
00279                     'write log entries to FILE (default is to not write log '
00280                         'files at all); use "syslog" to log to system log, '
00281                         'or "none" to disable logging',
00282                     metavar='FILE')
00283         self.choice(['log-level'], 
00284                     ['debug', 'info', 'warning', 'error', 'critical', 'fatal'],
00285                     'log at LEVEL, one of debug, info, warning, '
00286                         'error, critical, fatal (default: %default)',
00287                     metavar='LEVEL')
00288         self.bytesize(['log-max'], 
00289                       'rotate logs larger than SIZE, '
00290                         'zero for never (default: %default)',
00291                       metavar='SIZE', default=0)
00292         self.integer(['log-keep'], 'keep last N logs (%default)',
00293                      metavar='N', default=10)
00294         self.string(['log-mode'], 
00295                     'set permissions of new log files to MODE (octal; '
00296                         'default %default)',
00297                     metavar='MODE', default='0600')
00298 
00299         self.choice(['dump-memory-profile'],
00300                     ['simple', 'none', 'meliae', 'heapy'],
00301                     'make memory profiling dumps using METHOD, which is one '
00302                         'of: none, simple, meliae, or heapy '
00303                         '(default: %default)',
00304                     metavar='METHOD')

Here is the call graph for this function:

def cliapp.settings.Settings._add_setting (   self,
  setting 
) [private]
Add a setting to self._cp.

Definition at line 305 of file settings.py.

00305 
00306     def _add_setting(self, setting):
00307         '''Add a setting to self._cp.'''
00308 
00309         self._canonical_names.append(setting.names[0])
00310         for name in setting.names:
00311             self._settingses[name] = setting

Here is the caller graph for this function:

Return list of default config files to read.

The names of the files are dependent on the name of the program,
as set in the progname attribute.

The files may or may not exist.

Definition at line 548 of file settings.py.

00548 
00549     def _default_config_files(self):
00550         '''Return list of default config files to read.
00551         
00552         The names of the files are dependent on the name of the program,
00553         as set in the progname attribute.
00554         
00555         The files may or may not exist.
00556         
00557         '''
00558         
00559         configs = []
00560         
00561         configs.append('/etc/%s.conf' % self.progname)
00562         configs += self._listconfs('/etc/%s' % self.progname)
00563         configs.append(os.path.expanduser('~/.%s.conf' % self.progname))
00564         configs += self._listconfs(
00565                         os.path.expanduser('~/.config/%s' % self.progname))
00566         
00567         return configs

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings._destname (   self,
  name 
) [private]

Definition at line 396 of file settings.py.

00396 
00397     def _destname(self, name):
00398         name = '_'.join(name.split('-'))
00399         return name

Here is the call graph for this function:

def cliapp.settings.Settings._generate_manpage (   self,
  o,
  os,
  value,
  p 
) [private]

Definition at line 631 of file settings.py.

00631 
00632     def _generate_manpage(self, o, os, value, p): # pragma: no cover
00633         template = open(value).read()
00634         generator = ManpageGenerator(template, p, self._arg_synopsis,
00635                                      self._cmd_synopsis)
00636         sys.stdout.write(generator.format_template())
00637         sys.exit(0)

Definition at line 587 of file settings.py.

00587 
00588     def _get_config_files(self):
00589         if self._config_files is None:
00590             self._config_files = self._default_config_files
00591         return self._config_files

Here is the call graph for this function:

def cliapp.settings.Settings._listconfs (   self,
  dirname,
  listdir = os.listdir 
) [private]
Return list of pathnames to config files in dirname.

Config files are expectd to have names ending in '.conf'.

If dirname does not exist or is not a directory, 
return empty list.

Definition at line 568 of file settings.py.

00568 
00569     def _listconfs(self, dirname, listdir=os.listdir):
00570         '''Return list of pathnames to config files in dirname.
00571         
00572         Config files are expectd to have names ending in '.conf'.
00573         
00574         If dirname does not exist or is not a directory, 
00575         return empty list.
00576         
00577         '''
00578         
00579         if not os.path.isdir(dirname):
00580             return []
00581 
00582         basenames = listdir(dirname)
00583         basenames.sort(key=lambda s: [ord(c) for c in s])
00584         return [os.path.join(dirname, x)
00585                 for x in basenames
00586                 if x.endswith('.conf')]

Here is the caller graph for this function:

def cliapp.settings.Settings._option_names (   self,
  names 
) [private]
Turn setting names into option names.

Names with a single letter are short options, and get prefixed
with one dash. The rest get prefixed with two dashes.

Definition at line 385 of file settings.py.

00385 
00386     def _option_names(self, names):
00387         '''Turn setting names into option names.
00388         
00389         Names with a single letter are short options, and get prefixed
00390         with one dash. The rest get prefixed with two dashes.
00391         
00392         '''
00393 
00394         return ['--%s' % name if len(name) > 1 else '-%s' % name
00395                 for name in names]

def cliapp.settings.Settings._set_config_files (   self,
  config_files 
) [private]

Definition at line 592 of file settings.py.

00592 
00593     def _set_config_files(self, config_files):
00594         self._config_files = config_files
        
Return a ConfigParser instance with current values of settings.

Definition at line 638 of file settings.py.

00638 
00639     def as_cp(self):
00640         '''Return a ConfigParser instance with current values of settings.'''
00641         cp = ConfigParser.ConfigParser()
00642         cp.add_section('config')
00643         for name in self._canonical_names:
00644             cp.set('config', name, self._settingses[name].format())
00645 
00646         for section in self._cp.sections():
00647             if section != 'config':
00648                 cp.add_section(section)
00649                 for option in self._cp.options(section):
00650                     value = self._cp.get(section, option)
00651                     cp.set(section, option, value)
00652 
00653         return cp

Here is the caller graph for this function:

def cliapp.settings.Settings.boolean (   self,
  names,
  help,
  default = False,
  kwargs 
)
Add a setting with a boolean value.

Definition at line 339 of file settings.py.

00339 
00340     def boolean(self, names, help, default=False, **kwargs):
00341         '''Add a setting with a boolean value.'''
00342         self._add_setting(BooleanSetting(names, default, help, **kwargs))

Here is the call graph for this function:

def cliapp.settings.Settings.build_parser (   self,
  configs_only = False,
  arg_synopsis = None,
  cmd_synopsis = None 
)
Build OptionParser for parsing command line.

Definition at line 401 of file settings.py.

00401 
00402                      cmd_synopsis=None):
00403         '''Build OptionParser for parsing command line.'''
00404 
00405         maybe = lambda func: (lambda *args: None) if configs_only else func
00406 
00407         def getit(x):
00408             if x is None or type(x) in [str, unicode]:
00409                 return x
00410             else:
00411                 return x()
00412         usage = getit(self.usage)
00413         description = getit(self.description)
00414         p = optparse.OptionParser(prog=self.progname, version=self.version,
00415                                   formatter=FormatHelpParagraphs(),
00416                                   usage=usage,
00417                                   description=description,
00418                                   epilog=self.epilog)
00419         
00420         def dump_setting_names(*args): # pragma: no cover
00421             for name in self._canonical_names:
00422                 sys.stdout.write('%s\n' % name)
00423             sys.exit(0)
00424 
00425         p.add_option('--dump-setting-names',
00426                      action='callback',
00427                      nargs=0,
00428                      callback=maybe(dump_setting_names),
00429                      help='write out all names of settings and quit')
00430 
00431         def call_dump_config(*args): # pragma: no cover
00432             self.dump_config(sys.stdout)
00433             sys.exit(0)
00434 
00435         p.add_option('--dump-config',
00436                      action='callback',
00437                      nargs=0,
00438                      callback=maybe(call_dump_config),
00439                      help='write out the entire current configuration')
00440 
00441         def reset_configs(option, opt_str, value, parser):
00442             self.config_files = []
00443 
00444         p.add_option('--no-default-configs',
00445                      action='callback',
00446                      nargs=0,
00447                      callback=reset_configs,
00448                      help='clear list of configuration files to read')
00449 
00450         def append_to_configs(option, opt_str, value, parser):
00451             self.config_files.append(value)
00452 
00453         p.add_option('--config',
00454                      action='callback',
00455                      nargs=1,
00456                      type='string',
00457                      callback=append_to_configs,
00458                      help='add FILE to config files',
00459                      metavar='FILE')
00460 
00461         def list_config_files(*args): # pragma: no cover
00462             for filename in self.config_files:
00463                 print filename
00464             sys.exit(0)
00465 
00466         p.add_option('--list-config-files',
00467                      action='callback',
00468                      nargs=0,
00469                      callback=maybe(list_config_files),
00470                      help='list all possible config files')
00471 
00472         self._arg_synopsis = arg_synopsis
00473         self._cmd_synopsis = cmd_synopsis
00474         p.add_option('--generate-manpage',
00475                      action='callback',
00476                      nargs=1,
00477                      type='string',
00478                      callback=maybe(self._generate_manpage),
00479                      help='fill in manual page TEMPLATE',
00480                      metavar='TEMPLATE')
00481 
00482         def set_value(option, opt_str, value, parser, setting):
00483             if setting.action == 'append':
00484                 if setting.using_default_value:
00485                     setting.value = [value]
00486                 else:
00487                     setting.value += [value]
00488             elif setting.action == 'store_true':
00489                 setting.value = True
00490             else:
00491                 assert setting.action == 'store'
00492                 setting.value = value
00493 
00494         def add_option(obj, s):
00495             option_names = self._option_names(s.names)
00496             obj.add_option(*option_names, 
00497                            action='callback',
00498                            callback=maybe(set_value),
00499                            callback_args=(s,),
00500                            type=s.type,
00501                            nargs=s.nargs,
00502                            choices=s.choices,
00503                            help=s.help,
00504                            metavar=s.metavar)
00505         
00506         for name in self._canonical_names:
00507             s = self._settingses[name]
00508             if s.group is None:
00509                 add_option(p, s)
00510                 p.set_defaults(**{self._destname(name): s.value})
00511 
00512         groups = {}
00513         for name in self._canonical_names:
00514             s = self._settingses[name]
00515             if s.group is not None:
00516                 groups[s.group] = groups.get(s.group, []) + [(name, s)]
00517 
00518         groupnames = sorted(groups.keys())
00519         for groupname in groupnames:
00520             group = optparse.OptionGroup(p, groupname)
00521             p.add_option_group(group)
00522             for name, s in groups[groupname]:
00523                 add_option(group, s)
00524                 p.set_defaults(**{self._destname(name): s.value})
00525 
00526         return p

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings.bytesize (   self,
  names,
  help,
  default = 0,
  kwargs 
)
Add a setting with a size in bytes.

The user can use suffixes for kilo/mega/giga/tera/kibi/mibi/gibi/tibi.

Definition at line 343 of file settings.py.

00343 
00344     def bytesize(self, names, help, default=0, **kwargs):
00345         '''Add a setting with a size in bytes.
00346         
00347         The user can use suffixes for kilo/mega/giga/tera/kibi/mibi/gibi/tibi.
00348         
00349         '''
00350         
00351         self._add_setting(ByteSizeSetting(names, default, help, **kwargs))

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings.choice (   self,
  names,
  possibilities,
  help,
  kwargs 
)
Add a setting which chooses from list of acceptable values.

An example would be an option to set debugging level to be
one of a set of accepted names: debug, info, warning, etc.

The default value is the first possibility.

Definition at line 327 of file settings.py.

00327 
00328     def choice(self, names, possibilities, help, **kwargs):
00329         '''Add a setting which chooses from list of acceptable values.
00330         
00331         An example would be an option to set debugging level to be
00332         one of a set of accepted names: debug, info, warning, etc.
00333         
00334         The default value is the first possibility.
00335         
00336         '''
00337 
00338         self._add_setting(ChoiceSetting(names, possibilities, help, **kwargs))

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings.dump_config (   self,
  output 
)

Definition at line 654 of file settings.py.

00654 
00655     def dump_config(self, output): # pragma: no cover
00656         cp = self.as_cp()
00657         cp.write(output)
00658 

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings.integer (   self,
  names,
  help,
  default = 0,
  kwargs 
)
Add an integer setting.

Definition at line 352 of file settings.py.

00352 
00353     def integer(self, names, help, default=0, **kwargs):
00354         '''Add an integer setting.'''
00355         self._add_setting(IntegerSetting(names, default, help, **kwargs))

Here is the call graph for this function:

Here is the caller graph for this function:

Return canonical settings names.

Definition at line 370 of file settings.py.

00370 
00371     def keys(self):
00372         '''Return canonical settings names.'''
00373         return self._canonical_names[:]

def cliapp.settings.Settings.load_configs (   self,
  open = open 
)
Load all config files in self.config_files.

Silently ignore files that do not exist.

Definition at line 603 of file settings.py.

00603 
00604     def load_configs(self, open=open):
00605         '''Load all config files in self.config_files.
00606         
00607         Silently ignore files that do not exist.
00608         
00609         '''
00610 
00611         cp = ConfigParser.ConfigParser()
00612         cp.add_section('config')
00613 
00614         for pathname in self.config_files:
00615             try:
00616                 f = open(pathname)
00617             except IOError:
00618                 pass
00619             else:
00620                 cp.readfp(f)
00621                 f.close()
00622 
00623         for name in cp.options('config'):
00624             value = cp.get('config', name)
00625             s = self.set_from_raw_string(name, value)
00626             if hasattr(s, 'using_default_value'):
00627                 s.using_default_value = True
00628 
00629         # Remember the ConfigParser for use in as_cp later on.
00630         self._cp = cp

Here is the call graph for this function:

def cliapp.settings.Settings.parse_args (   self,
  args,
  parser = None,
  suppress_errors = False,
  configs_only = False,
  arg_synopsis = None,
  cmd_synopsis = None 
)
Parse the command line.

Return list of non-option arguments. ``args`` would usually
be ``sys.argv[1:]``.

Definition at line 529 of file settings.py.

00529 
00530                     cmd_synopsis=None):
00531         '''Parse the command line.
00532         
00533         Return list of non-option arguments. ``args`` would usually
00534         be ``sys.argv[1:]``.
00535         
00536         '''
00537 
00538         p = parser or self.build_parser(configs_only=configs_only,
00539                                         arg_synopsis=arg_synopsis,
00540                                         cmd_synopsis=cmd_synopsis)
00541 
00542         if suppress_errors:
00543             p.error = lambda msg: sys.exit(1)
00544 
00545         options, args = p.parse_args(args)
00546         return args

Here is the call graph for this function:

def cliapp.settings.Settings.require (   self,
  name 
)
Raise exception if setting has not been set.

Option must have a value, and a default value is OK.

Definition at line 374 of file settings.py.

00374 
00375     def require(self, name):
00376         '''Raise exception if setting has not been set.
00377         
00378         Option must have a value, and a default value is OK.
00379         
00380         '''
00381         
00382         if not self._settingses[name].has_value():
00383             raise cliapp.AppException('Setting %s has no value, '
00384                                         'but one is required' % name)
        
def cliapp.settings.Settings.set_from_raw_string (   self,
  name,
  raw_string 
)
Set value of a setting from a raw, unparsed string value.

Definition at line 597 of file settings.py.

00597 
00598     def set_from_raw_string(self, name, raw_string):
00599         '''Set value of a setting from a raw, unparsed string value.'''
00600         s = self._settingses[name]
00601         s.parse_value(raw_string)
00602         return s

Here is the caller graph for this function:

def cliapp.settings.Settings.string (   self,
  names,
  help,
  default = '',
  kwargs 
)
Add a setting with a string value.

Definition at line 312 of file settings.py.

00312 
00313     def string(self, names, help, default='', **kwargs):
00314         '''Add a setting with a string value.'''
00315         self._add_setting(StringSetting(names, default, help, **kwargs))

Here is the call graph for this function:

Here is the caller graph for this function:

def cliapp.settings.Settings.string_list (   self,
  names,
  help,
  default = None,
  kwargs 
)
Add a setting which have multiple string values.

An example would be an option that can be given multiple times
on the command line, e.g., "--exclude=foo --exclude=bar".

Definition at line 316 of file settings.py.

00316 
00317     def string_list(self, names, help, default=None, **kwargs):
00318         '''Add a setting which have multiple string values.
00319         
00320         An example would be an option that can be given multiple times
00321         on the command line, e.g., "--exclude=foo --exclude=bar".
00322         
00323         '''
00324 
00325         self._add_setting(StringListSetting(names, default or [], help,
00326                                             **kwargs))

Here is the call graph for this function:


Member Data Documentation

Definition at line 471 of file settings.py.

Definition at line 259 of file settings.py.

Definition at line 472 of file settings.py.

Definition at line 269 of file settings.py.

Definition at line 270 of file settings.py.

Definition at line 258 of file settings.py.

Definition at line 264 of file settings.py.

Definition at line 265 of file settings.py.

Definition at line 262 of file settings.py.

Definition at line 263 of file settings.py.

Definition at line 261 of file settings.py.


Property Documentation

Definition at line 595 of file settings.py.


The documentation for this class was generated from the following file: