Python getopt.gnu_getopt() Examples

The following are 26 code examples of getopt.gnu_getopt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module getopt , or try the search function .
Example #1
Source File: test_getopt.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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']) 
Example #2
Source File: test_getopt.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #3
Source File: tldr.py    From tldr-alfred with MIT License 6 votes vote down vote up
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 
Example #4
Source File: test_getopt.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #5
Source File: test_getopt.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #6
Source File: twitter-to-xhtml.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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) 
Example #7
Source File: qi.py    From aws-support-tools with Apache License 2.0 6 votes vote down vote up
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() 
Example #8
Source File: test_getopt.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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']) 
Example #9
Source File: test_getopt.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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']) 
Example #10
Source File: test_getopt.py    From BinderFilter with MIT License 6 votes vote down vote up
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']) 
Example #11
Source File: test_getopt.py    From oss-ftp with MIT License 6 votes vote down vote up
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']) 
Example #12
Source File: start.py    From vlcp with Apache License 2.0 6 votes vote down vote up
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() 
Example #13
Source File: test_getopt.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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']) 
Example #14
Source File: options.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #15
Source File: command.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #16
Source File: tweet.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
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) 
Example #17
Source File: script.py    From vlcp with Apache License 2.0 5 votes vote down vote up
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__,)) 
Example #18
Source File: update_hosts.py    From ipv6-hosts with MIT License 5 votes vote down vote up
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' 
Example #19
Source File: optval.py    From gitinspector with GNU General Public License v3.0 5 votes vote down vote up
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". 
Example #20
Source File: optval.py    From gitinspector with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #21
Source File: emote.py    From EmoteCollector with GNU Affero General Public License v3.0 4 votes vote down vote up
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) 
Example #22
Source File: Options.py    From broc with Apache License 2.0 4 votes vote down vote up
def OptionBuild(argv):
    """
    Get build or test options.
    Args:
        argv : command line argv
    Return:
        None : fail
        options : build or test options
        options["all_log"] : show all build log
        options["mode"] : debug or release
        options["path"] : modular path
        options["jobs"] : the number of build threads
    """
    options = dict()
    options["all_log"] = False
    options["path"] = ""
    options["mode"] = "debug"
    options["jobs"] = 4

    try:
        opts, args = getopt.gnu_getopt(argv, "", ["all-log", "mode=", "jobs="])
    except getopt.GetoptError as ex:
        Log.colorprint("DEFAULT", "%s\nType '%s help' for usage" % \
                (str(ex), os.path.basename(sys.argv[0])), False)
        return None

    if len(args) <= 0:
        options["path"] = os.getcwd()
    elif len(args) == 1:
        options["path"] = args[0]
    else:
        Log.colorprint("RED", "invalid arguments %s\nType '%s help' for usage" % \
                (str(args), os.path.basename(sys.argv[0])), False)
        return None
    
    for opt, arg in opts:
        if opt == "--all-log":
            options["all_log"] = True
            continue
        if opt == "--mode":
            if arg != "debug" and arg != "release":
                Log.colorprint("RED", "invalid mode %s. Please use debug or release" % arg, False)
                return None
            options["mode"] = arg
            continue
        if opt == "--jobs":
            options["jobs"] = int(arg)
            continue
        return None

    return options 
Example #23
Source File: tweet-tokenize.py    From deepnl with GNU General Public License v3.0 4 votes vote down vote up
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)) 
Example #24
Source File: strace2elastic.py    From strace2elastic with MIT License 4 votes vote down vote up
def main(argv):
    input_file = None
    elastic_host = None
    container = None

    # Parse the command-line options
    try:
        options, remainder = getopt.gnu_getopt(argv, 'hec:',
                ['help', 'elastichost=', 'container='])

        for opt, arg in options:
            if opt in ('-h', '--help'):
                usage()
                return
            elif opt in ('-e', '--elastichost'):
                elastic_host = arg
            elif opt in ('-c', '--container'):
                container = arg

        if len(remainder) > 1:
            print remainder
            raise Exception("Too many options")
        elif len(remainder) == 1:
            input_file = remainder[0]
    except Exception as e:
        sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), e))
        sys.exit(1)

    if container is None or container == "":
        sys.stderr.write("container name cannot be empty\n")
        sys.exit(1)

    # Parse strace output and add to elastic search
    try:
        sys2elastic(input_file, container, elastic_host)
    except IOError as e:
        sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), e))
        sys.exit(1)

#
# Entry point to the application
# 
Example #25
Source File: dipspades_logic.py    From SqueezeMeta with GNU General Public License v3.0 4 votes vote down vote up
def parse_arguments(argv, log):
    try:
        options, not_options = getopt.gnu_getopt(argv, DS_Args_List.short_options, DS_Args_List.long_options)
    except getopt.GetoptError:
        _, exc, _ = sys.exc_info()
        sys.stderr.write(str(exc) + "\n")
        sys.stderr.flush()
        options_storage.usage("", dipspades=True)
        sys.exit(1)

    ds_args = DS_Args()
    for opt, arg in options:
        if opt == '-o':
            ds_args.output_dir = abspath(expanduser(arg))
        elif opt == '--expect-gaps':
            ds_args.allow_gaps = True
        elif opt == '--expect-rearrangements':
            ds_args.weak_align = True
        elif opt == '--hap':
            ds_args.haplocontigs_fnames.append(support.check_file_existence(arg, 'haplocontigs', log, dipspades=True))
        elif opt == '-t' or opt == "--threads":
            ds_args.max_threads = int(arg)
        elif opt == '-m' or opt == "--memory":
            ds_args.max_memory = int(arg)
        elif opt == '--tmp-dir':
            ds_args.tmp_dir = abspath(expanduser(arg))
        elif opt == '--dsdebug':
            ds_args.dev_mode = True
        elif opt == '--hap-assembly':
            ds_args.haplotype_assembly = True
        elif opt == '--dsK':
            ds_args.k = int(arg)
        elif opt == '--saves':
            ds_args.saves = os.path.abspath(arg)
            ds_args.dev_mode = True
        elif opt == '--start-from':
            ds_args.start_from = ParseStartPoint(arg, log)
            ds_args.dev_mode = True
    ds_args.haplocontigs = os.path.join(ds_args.output_dir, "haplocontigs")

    if not ds_args.output_dir:
        support.error("the output_dir is not set! It is a mandatory parameter (-o output_dir).", log, dipspades=True)
    if not ds_args.haplocontigs_fnames and ds_args.start_from == 'dipspades':
        support.error("cannot start dipSPAdes without at least one haplocontigs file!", log, dipspades=True)
    if not ds_args.tmp_dir:
        ds_args.tmp_dir = os.path.join(ds_args.output_dir, options_storage.TMP_DIR)

    if ds_args.start_from != 'dipspades' and ds_args.saves == '':
        support.error("saves were not defined! dipSPAdes can not start from " + ds_args.start_from)

    return ds_args 
Example #26
Source File: dev_appserver_main.py    From browserscope with Apache License 2.0 4 votes vote down vote up
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)