本文整理汇总了Python中optparse.Option类的典型用法代码示例。如果您正苦于以下问题:Python Option类的具体用法?Python Option怎么用?Python Option使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Option类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__( self, *args, **kwargs ):
try:
ltype = kwargs.pop('ltype')
except:
ltype = None
Option.__init__( self, *args, **kwargs )
self.ltype = ltype
示例2: parse_reqs
def parse_reqs(reqs_file):
''' parse the requirements '''
options = Option("--workaround")
options.skip_requirements_regex = None
options.isolated_mode = True
install_reqs = parse_requirements(reqs_file, options=options, session=PipSession())
return [str(ir.req) for ir in install_reqs]
示例3: take_action
def take_action(self, action, dest, opt, value, values, parser):
if action == "pubsub":
# read the subscriber and publisher arguments
value += " "
for arg in parser.rargs:
if arg[:2] == "--" and len(arg) > 2: break
if arg[:1] == "-" and len(arg) > 1: break
value += arg + " "
subpubArray = [ x.strip() for x in value.split(",") if x.strip() ]
# verify that argument meets requirements
if len(subpubArray) == 2:
values.ensure_value(dest, []).append({"name": subpubArray[0], "type": subpubArray[1]})
else:
if opt == '-s': exitWithError(ERROR_OPT.SUBSCRIBER_MISSING, len(subpubArray))
if opt == '-p': exitWithError(ERROR_OPT.PUBLISHER_MISING, len(subpubArray))
elif action == "strspaces":
# read the subscriber and publisher arguments
for arg in parser.rargs:
if arg[:2] == "--" and len( arg ) > 2: break
if arg[:1] == "-" and len( arg ) > 1: break
value += " " + arg
setattr(values, dest, value )
else:
Option.take_action(self, action, dest, opt, value, values, parser)
示例4: take_action
def take_action(self, action, dest, opt, value, values, parser):
"""
This function is a wrapper to take certain options passed on command
prompt and wrap them into an Array.
@param action: The type of action that will be taken. For example:
"store_true", "store_false", "extend".
@type action: String
@param dest: The name of the variable that will be used to store the
option.
@type dest: String/Boolean/Array
@param opt: The option string that triggered the action.
@type opt: String
@param value: The value of opt(option) if it takes a
value, if not then None.
@type value:
@param values: All the opt(options) in a dictionary.
@type values: Dictionary
@param parser: The option parser that was orginally called.
@type parser: OptionParser
"""
if (action == "extend") :
value_list = []
try:
for v in value.split(","):
# Need to add code for dealing with paths if there is option for paths.
new_value = value.strip().rstrip()
if (len(new_value) > 0):
value_list.append(new_value)
except:
pass
else:
values.ensure_value(dest, []).extend(value_list)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
示例5: take_action
def take_action(self, action, dest, opt, value, values, parser):
if action == 'extend':
split_value = value.split(',')
ensure_value(qconfig, dest, []).extend(split_value)
else:
Option.take_action(
self, action, dest, opt, value, qconfig, parser)
示例6: _set_attrs
def _set_attrs(self, attrs):
"""overwrite _set_attrs to allow store_or callbacks"""
Option._set_attrs(self, attrs)
if self.action in self.EXTOPTION_STORE_OR:
setattr(self, 'store_or', self.action)
def store_or(option, opt_str, value, parser, *args, **kwargs):
"""Callback for supporting options with optional values."""
# see http://stackoverflow.com/questions/1229146/parsing-empty-options-in-python
# ugly code, optparse is crap
if parser.rargs and not parser.rargs[0].startswith('-'):
val = parser.rargs[0]
parser.rargs.pop(0)
else:
val = kwargs.get('orig_default', None)
setattr(parser.values, option.dest, val)
# without the following, --x=y doesn't work; only --x y
self.nargs = 0 # allow 0 args, will also use 0 args
if self.type is None:
# set to not None, for takes_value to return True
self.type = 'string'
self.callback = store_or
self.callback_kwargs = {'orig_default': copy.deepcopy(self.default),
}
self.action = 'callback' # act as callback
if self.store_or == 'store_or_None':
self.default = None
else:
raise ValueError("_set_attrs: unknown store_or %s" % self.store_or)
示例7: take_action
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(
self, action, dest, opt, value, values, parser)
示例8: take_action
def take_action(self, action, dest, opt, value, values, parser):
if action == "map":
values.ensure_value(dest, parser.map[opt.lstrip('-')])
elif action == "map_extend":
values.ensure_value(dest, []).extend(parser.map[opt.lstrip('-')])
else:
Option.take_action(self, action, dest, opt, value, values, parser)
示例9: __init__
def __init__(self, *opt_str, **attrs):
"""
*opt_str: Same meaning as in twitter.common.options.Option, at least one is required.
**attrs: See twitter.common.options.Option, with the following caveats:
Exactly one of the following must be provided:
clusters: A static Clusters object from which to pick clusters.
cluster_provider: A function that takes a cluster name and returns a Cluster object.
"""
self.clusters = attrs.pop('clusters', None)
self.cluster_provider = attrs.pop('cluster_provider', None)
if not (self.clusters is not None) ^ (self.cluster_provider is not None):
raise ValueError('Must specify exactly one of clusters and cluster_provider.')
default_attrs = dict(
default=None,
action='store',
type='mesos_cluster',
help='Mesos cluster to use (Default: %%default)'
)
combined_attrs = default_attrs
combined_attrs.update(attrs) # Defensive copy
Option.__init__(self, *opt_str, **combined_attrs) # old-style superclass
示例10: take_action
def take_action(self,action,dest,opt,value,values,parser):
log.debug('take_action: %s',action)
if action in custom_actions:
custom_actions.get(action)(dest,value,values)
else:
Option.take_action(self,action,dest,opt,value,values,parser)
log.debug('values: %s',values)
示例11: take_action
def take_action(self, action, dest, opt, value, values, parser):
"Extended to handle generation a config file"
if action == "generate_config":
parser.generate_and_print_config_file()
parser.exit()
Option.take_action(self, action, dest, opt, value, values, parser)
示例12: __init__
def __init__(self, opt, *args, **kwargs):
if 'dest' not in kwargs:
# Override default dest, which would strip first two characters:
kwargs['dest'] = opt.replace('-', '_')
self.group = kwargs['group']
del kwargs['group']
Option.__init__(self, opt, *args, **kwargs)
示例13: _check_dest
def _check_dest(self):
try:
Option._check_dest(self)
except IndexError:
if self.subopt:
self.dest = "__%s__%s" % (self.baseopt, self.subopt)
self.dest = self.dest.replace("-", "")
else:
raise
示例14: take_action
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
for token in lvalue:
token = token.strip()
if token:
values.ensure_value(dest, []).append(token)
else:
Option.take_action(
self, action, dest, opt, value, values, parser)
示例15: addOption
def addOption(self, *args, **kwargs):
mandatory = kwargs.pop('mandatory', False)
if 'help' in kwargs and 'default' in kwargs and '{default}' in kwargs['help']:
kwargs['help'] = kwargs['help'].format(default=kwargs['default'])
option = Option(*args, **kwargs)
if option.metavar is None:
option.metavar = '<{0}>'.format(option.type) if kwargs.get('default') is None else repr(option.default)
if mandatory:
self._mandatoryKeys.append(option.dest)
self._parser.add_option(option)