本文整理汇总了Python中getopt.gnu_getopt方法的典型用法代码示例。如果您正苦于以下问题:Python getopt.gnu_getopt方法的具体用法?Python getopt.gnu_getopt怎么用?Python getopt.gnu_getopt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类getopt
的用法示例。
在下文中一共展示了getopt.gnu_getopt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ParseArguments
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def ParseArguments(argv):
"""Parses command-line arguments.
Args:
argv: Command-line arguments, including the executable name, used to
execute this application.
Returns:
Tuple (args, option_dict) where:
args: List of command-line arguments following the executable name.
option_dict: Dictionary of parsed flags that maps keys from DEFAULT_ARGS
to their values, which are either pulled from the defaults, or from
command-line flags.
"""
option_dict = DEFAULT_ARGS.copy()
try:
opts, args = getopt.gnu_getopt(argv[1:], OPTIONS, LONG_OPTIONS)
except getopt.GetoptError, e:
print >>sys.stderr, 'Error: %s' % e
PrintUsageExit(1)
示例2: test_gnu_getopt
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def test_gnu_getopt(self):
# Test handling of GNU style scanning mode.
cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
# GNU style
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
self.assertEqual(args, ['arg1'])
self.assertEqual(opts, [('-a', ''), ('-b', '1'),
('--alpha', ''), ('--beta', '2')])
# recognize "-" as an argument
opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', [])
self.assertEqual(args, ['-'])
self.assertEqual(opts, [('-a', ''), ('-b', '-')])
# Posix style via +
opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
self.assertEqual(opts, [('-a', '')])
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
# Posix style via POSIXLY_CORRECT
self.env["POSIXLY_CORRECT"] = "1"
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
self.assertEqual(opts, [('-a', '')])
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
示例3: parsearg
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def parsearg():
try:
options, args = getopt.gnu_getopt(sys.argv[1:], 'f:p:F:?hd', 'help')
configfile = None
pidfile = '/var/run/vlcp.pid'
daemon = False
fork = None
for k,v in options:
if k == '--help' or k == '-?' or k == '-h':
usage()
elif k == '-f':
configfile = v
elif k == '-p':
pidfile = v
elif k == '-d':
daemon = True
elif k == '-F':
fork = int(v)
startup = None
if args:
startup = args
return (configfile, daemon, pidfile, startup, fork)
except getopt.GetoptError as exc:
print(exc)
usage()
示例4: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def main():
option_list = 'region= type= role= key= volume= ami= bootstrap='.split()
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], '', option_list)
except:
usage()
sys.exit(2)
if len(args) > 0:
if args[0] == 'configure':
configure()
elif args[0] in os_list:
try:
launch(opts, args[0])
except NoCredentialsError:
advise_credentials()
except:
troubleshoot()
elif args[0] == 'help':
usage()
else:
usage()
else:
usage()
示例5: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def main():
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], 'ho', ['help', 'output='])
except getopt.GetoptError:
Usage()
sys.exit(2)
try:
user = args[0]
except:
Usage()
sys.exit(2)
output = None
for o, a in opts:
if o in ("-h", "--help"):
Usage()
sys.exit(2)
if o in ("-o", "--output"):
output = a
FetchTwitter(user, output)
示例6: parse_args
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def parse_args(query=''):
query = query.split()
dic = {
'isUpdate': False,
'platform': default_platform,
'command': ''
}
try:
opts, args = getopt.gnu_getopt(query, 'uo:')
except:
return dic
for opt, arg in opts:
if opt == '-u':
dic['isUpdate'] = True
elif opt == '-o':
dic['platform'] = arg
dic['command'] = '-'.join(args)
return dic
示例7: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def main(cls):
short_opts = 'f:h?'
long_opts = ['help']
short_dict = {}
for opt in cls.options:
hasarg = len(opt) < 3 or opt[2]
if hasarg:
if len(opt) > 1 and opt[1]:
short_opts += opt[1] + ':'
short_dict[opt[1]] = opt[0]
long_opts.append(opt[0] + '=')
else:
if len(opt) > 1 and opt[1]:
short_opts += opt[1]
short_dict[opt[1]] = opt[0]
long_opts.append(opt[0])
try:
options, args = getopt.gnu_getopt(sys.argv[1:], short_opts, long_opts)
except Exception as exc:
print(str(exc))
print()
print(cls.__doc__)
sys.exit(2)
else:
opt_dict = {}
configfile = None
for k,v in options:
if k == '--help' or k == '-?' or k == '-h':
print(cls.__doc__)
sys.exit(0)
elif k == '-f':
configfile = v
else:
if k.startswith('--'):
opt_dict[k[2:]] = v
else:
opt_dict[short_dict[k[1:]]] = v
from vlcp.config import manager
manager['main.args'] = args
manager['main.kwargs'] = opt_dict
server_main(configfile, ('__main__.' + cls.__name__,))
示例8: __find_options_to_extend__
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def __find_options_to_extend__(long_options):
options_to_extend = []
for num, arg in enumerate(long_options):
arg = arg.split(":")
if len(arg) == 2:
long_options[num] = arg[0] + "="
options_to_extend.append(("--" + arg[0], arg[1]))
return options_to_extend
# This is a duplicate of gnu_getopt, but with support for optional arguments in long options, in the form; "arg:default_value".
示例9: gnu_getopt
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def gnu_getopt(args, options, long_options):
options_to_extend = __find_options_to_extend__(long_options)
for num, arg in enumerate(args):
opt = __find_arg_in_options__(arg, options_to_extend)
if opt:
args[num] = arg + "=" + opt[1]
return getopt.gnu_getopt(args, options, long_options)
示例10: __init__
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def __init__(self, optspec, optfunc=getopt.gnu_getopt,
onabort=_default_onabort):
self.optspec = optspec
self._onabort = onabort
self.optfunc = optfunc
self._aliases = {}
self._shortopts = 'h?'
self._longopts = ['help', 'usage']
self._hasparms = {}
self._defaults = {}
self._usagestr = self._gen_usage()
示例11: get_config
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def get_config():
shortopts = 'hs:o:t:n:c'
longopts = ['help', 'cname']
try:
optlist, args = getopt.gnu_getopt(sys.argv[1:], shortopts, longopts)
except getopt.GetoptError as e:
print(e)
print_help()
sys.exit(1)
global config
for key, value in optlist:
if key == '-s':
config['dns'] = value
elif key == '-o':
config['outfile'] = value
elif key == '-t':
config['querytype'] = value
elif key in ('-c', '--cname'):
config['cname'] = True
elif key == '-n':
config['threadnum'] = int(value)
elif key in ('-h', '--help'):
print_help()
sys.exit(0)
if len(args) != 1:
print("You must specify the input hosts file (only one).")
sys.exit(1)
config['infile'] = args[0]
if config['outfile'] == '':
config['outfile'] = config['infile'] + '.out'
示例12: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def main():
try:
shortflags = 'h'
longflags = ['help', 'username=', 'password=', 'encoding=']
opts, args = getopt.gnu_getopt(sys.argv[1:], shortflags, longflags)
except getopt.GetoptError:
PrintUsageAndExit()
usernameflag = None
passwordflag = None
encoding = None
for o, a in opts:
if o in ("-h", "--help"):
PrintUsageAndExit()
if o in ("--username"):
usernameflag = a
if o in ("--password"):
passwordflag = a
if o in ("--encoding"):
encoding = a
message = ' '.join(args)
if not message:
PrintUsageAndExit()
rc = TweetRc()
username = usernameflag or GetUsernameEnv() or rc.GetUsername()
password = passwordflag or GetPasswordEnv() or rc.GetPassword()
if not username or not password:
PrintUsageAndExit()
api = twitter.Api(username=username, password=password, input_encoding=encoding)
try:
status = api.PostUpdate(message)
except UnicodeDecodeError:
print "Your message could not be encoded. Perhaps it contains non-ASCII characters? "
print "Try explicitly specifying the encoding with the --encoding flag"
sys.exit(2)
print "%s just posted: %s" % (status.user.name, status.text)
示例13: parse_options
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def parse_options(self, *args):
'''Parse commandline options for this command
Sets the attributes 'args' and 'opts' to a list of arguments
and a dictionary of options respectively
@param args: all remaining options to be parsed
@raises GetOptError: when options are not correct
'''
options = ''
long_options = []
options_map = {}
for l, s, desc in self.default_options + self.options:
long_options.append(l)
if s and l.endswith('='):
options += s + ':'
options_map[s] = l.strip('=')
elif s:
options += s
options_map[s] = l
optlist, args = gnu_getopt(args, options, long_options)
self.args += args
for o, a in optlist:
key = o.strip('-')
key = options_map.get(key, key)
if a == '':
self.opts[key] = True
elif key in self.opts and isinstance(self.opts[key], list):
self.opts[key].append(a)
else:
self.opts[key] = a
示例14: main
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def main():
scriptname = os.path.basename(sys.argv[0])
try:
long_opts = ['language=', 'help', 'usage']
opts, args = getopt.gnu_getopt(sys.argv[1:], 'l:h', long_opts)
except getopt.GetoptError:
show_usage(scriptname)
show_suggestion(scriptname)
sys.exit(1)
lang = 'english'
for opt, arg in opts:
if opt in ('-l', '--language'):
lang = arg
elif opt in ('-h', '--help'):
show_help()
return
elif opt == '--usage':
show_usage(scriptname)
return
# Tanl modules
splitterModel = data + 'split/sentence/' + lang + '.punkt'
if os.path.exists(splitterModel):
print("No such model:" + splitterModel)
return
t0 = SentenceSplitter(splitterModel)
t1 = Tokenizer()
# Field containig tweets
text_field = 3
for line in sys.stdin:
fields = line.split('\t')
p0 = t0.pipe([fields[text_field]]) # SentenceSplitter
p1 = t1.pipe(p0) # Tokenizer
tokens = []
for t in p1:
form = t['FORM']
if form != '\n':
tokens.append(form)
fields[text_field] = ' '.join(tokens)
print('\t'.join(fields))
示例15: remove
# 需要导入模块: import getopt [as 别名]
# 或者: from getopt import gnu_getopt [as 别名]
def remove(self, context, *names: commands.clean_content):
"""Removes one or more emotes from the bot. You must own all of them.
Optional arguments:
-f, --force Whether to forcibly remove the emotes. This option can only be used by emote moderators.
"""
try:
opts, names = getopt.gnu_getopt(names, 'f', ('force',))
except getopt.GetoptError:
opts = []
opts = frozenset(dict(opts))
force = False
if '-f' in opts or '--force' in opts:
if not await self.db.is_moderator(context.author.id):
return await context.send(_('Error: only emote moderators may forcibly remove emotes.'))
force = True
logger = (
(lambda emote: self.logger.on_emote_force_remove(emote, context.author))
if force
else self.logger.on_emote_remove)
if not names:
return await context.send(_('Error: you must provide the name of at least one emote to remove'))
messages = {}
async with context.typing():
for name in names:
arg = fr'\:{name}:'
try:
emote = await self.db.get_emote(name)
except BaseException as error: # XXX
messages.setdefault(self._humanize_errors(error), []).append(arg)
continue
# log the emote removal *first* because if we were to do it afterwards,
# the emote would not display (since it's already removed)
removal_messages = await logger(emote)
try:
await self.db.remove_emote(emote, context.author.id, force=force)
except (errors.ConnoisseurError, errors.DiscordError) as error:
messages.setdefault(self._humanize_errors(error), []).append(arg)
# undo the log
await asyncio.gather(*map(operator.methodcaller('delete'), removal_messages), return_exceptions=True)
else:
message = _('**Successfully deleted:**')
messages.setdefault((0, message), []).append(emote.escaped_name())
messages = sorted(messages.items())
message = self._format_errors(messages)
await context.send(message)