Python getopt.gnu_getopt() Examples

The following are code examples for showing how to use getopt.gnu_getopt(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser 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 2
Project: NiujiaoDebugger   Author: MrSrc   File: test_getopt.py    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
Project: smaslennikov.github.io   Author: smaslennikov   File: grep.py    MIT License 6 votes vote down vote up
def cmd_logs(data, buffer, args):
    """List files in Weechat's log dir."""
    cmd_init()
    global home_dir
    sort_by_size = False
    filter = []

    try:
        opts, args = getopt.gnu_getopt(args.split(), 's', ['size'])
        if args:
            filter = args
        for opt, var in opts:
            opt = opt.strip('-')
            if opt in ('size', 's'):
                sort_by_size = True
    except Exception, e:
        error('Argument error, %s' %e)
        return WEECHAT_RC_OK

    # is there's a filter, filter_excludes should be False 
Example 4
Project: smaslennikov.github.io   Author: smaslennikov   File: grep.py    MIT License 6 votes vote down vote up
def cmd_logs(data, buffer, args):
    """List files in Weechat's log dir."""
    cmd_init()
    global home_dir
    sort_by_size = False
    filter = []

    try:
        opts, args = getopt.gnu_getopt(args.split(), 's', ['size'])
        if args:
            filter = args
        for opt, var in opts:
            opt = opt.strip('-')
            if opt in ('size', 's'):
                sort_by_size = True
    except Exception, e:
        error('Argument error, %s' %e)
        return WEECHAT_RC_OK

    # is there's a filter, filter_excludes should be False 
Example 5
Project: ironpython2   Author: IronLanguages   File: test_getopt.py    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 6
Project: mlab-ns   Author: m-lab   File: gflags.py    Apache License 2.0 6 votes vote down vote up
def __init__(self):
    # Since everything in this class is so heavily overloaded, the only
    # way of defining and using fields is to access __dict__ directly.

    # Dictionary: flag name (string) -> Flag object.
    self.__dict__['__flags'] = {}
    # Dictionary: module name (string) -> list of Flag objects that are defined
    # by that module.
    self.__dict__['__flags_by_module'] = {}
    # Dictionary: module id (int) -> list of Flag objects that are defined by
    # that module.
    self.__dict__['__flags_by_module_id'] = {}
    # Dictionary: module name (string) -> list of Flag objects that are
    # key for that module.
    self.__dict__['__key_flags_by_module'] = {}

    # Set if we should use new style gnu_getopt rather than getopt when parsing
    # the args.  Only possible with Python 2.3+
    self.UseGnuGetOpt(False) 
Example 7
Project: oss-ftp   Author: aliyun   File: test_getopt.py    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 8
Project: vlcp   Author: hubo1016   File: start.py    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 9
Project: ave   Author: sonyxperiadev   File: job.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_opt(argv):
    (opts, args) = getopt.gnu_getopt(argv, 'j:e:t:', ['jobs=', 'env=', 'tags='])
    if args:
        args = ','.join(args)
        raise Exception('non-dashed options "%s" not recognized' % args)

    jobs_dir = None
    env_vars = []
    job_tags = []
    for (opt, arg) in opts:
        if   opt in ['-j', '--jobs']:
            jobs_dir = arg
        elif opt in ['-e', '--env']:
            env_vars = arg.split(',')
        elif opt in ['-t', '--tags']:
            job_tags = [a for a in arg.split(',') if a]

    if not jobs_dir:
        raise Exception('at least -j or --jobs must be specified')

    return (jobs_dir, job_tags, env_vars) 
Example 10
Project: ave   Author: sonyxperiadev   File: vcs.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_opt(argv):
    (opts, args) = getopt.gnu_getopt(
        argv, 's:r:d:t:', ['source=', 'refspec=', 'destination=', 'timeout=']
    )

    if args:
        args = ','.join(args)
        raise Exception('non-dashed options "%s" not recognized' % args)

    src     = None
    dst     = None
    refspec = None
    timeout = 600

    for (opt, arg) in opts:
        if   opt in ['-s', '--source']:
            src = arg
        elif opt in ['-r', '--refspec']:
            refspec = arg
        elif opt in ['-d', '--destination']:
            dst = arg
        elif opt in ['-t', '--timeout']:
            timeout = int(arg)

    return (src, dst, refspec, timeout) 
Example 11
Project: ave   Author: sonyxperiadev   File: job.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_opt(argv):
    (opts, args) = getopt.gnu_getopt(argv, 'j:e:t:', ['jobs=', 'env=', 'tags='])
    if args:
        args = ','.join(args)
        raise Exception('non-dashed options "%s" not recognized' % args)

    jobs_dir = None
    env_vars = []
    job_tags = []
    for (opt, arg) in opts:
        if   opt in ['-j', '--jobs']:
            jobs_dir = arg
        elif opt in ['-e', '--env']:
            env_vars = arg.split(',')
        elif opt in ['-t', '--tags']:
            job_tags = [a for a in arg.split(',') if a]

    if not jobs_dir:
        raise Exception('at least -j or --jobs must be specified')

    return (jobs_dir, job_tags, env_vars) 
Example 12
Project: ave   Author: sonyxperiadev   File: vcs.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_opt(argv):
    (opts, args) = getopt.gnu_getopt(
        argv, 's:r:d:t:', ['source=', 'refspec=', 'destination=', 'timeout=']
    )

    if args:
        args = ','.join(args)
        raise Exception('non-dashed options "%s" not recognized' % args)

    src     = None
    dst     = None
    refspec = None
    timeout = 600

    for (opt, arg) in opts:
        if   opt in ['-s', '--source']:
            src = arg
        elif opt in ['-r', '--refspec']:
            refspec = arg
        elif opt in ['-d', '--destination']:
            dst = arg
        elif opt in ['-t', '--timeout']:
            timeout = int(arg)

    return (src, dst, refspec, timeout) 
Example 13
Project: wikitweets   Author: iguanaonmystack   File: client.py    MIT License 6 votes vote down vote up
def main():
    """Main entry point for wikitweets"""
    do_twitter = True
    try:
        opts, args = getopt.gnu_getopt(
            sys.argv[1:], 'h', ['help', 'no-twitter'])
        for o, a in opts:
            if o in ('-h', '--help'):
                print usage()
                return 0
            if o in ('--no-twitter',):
                do_twitter = False
        if len(args) != 1:
            raise getopt.GetoptError('config file required.')
        config_filename = args[0]
    except getopt.GetoptError, e:
        print >> sys.stderr, e
        print >> sys.stderr, usage()
        return 2 
Example 14
Project: wikitweets   Author: iguanaonmystack   File: dump_category.py    MIT License 6 votes vote down vote up
def main():
    base = 'https://en.wikipedia.org'
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], 'w:h', ['wiki=', 'help'])
        for o, a in opts:
            if o in ('-w', '--wiki'):
                base = a
            if o in ('-h', '--help'):
                print usage()
                return 0
        if len(args) != 1:
            raise getopt.GetoptError('category name required.')
        category = sys.argv[1]
    except getopt.GetoptError, e:
        print >> sys.stderr, e
        print >> sys.stderr, usage()
        return 2 
Example 15
Project: painter-goblin   Author: ross-spencer   File: follow.py    GNU General Public License v3.0 6 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'followers', 'following', 'api-rate', 'ids']
    short_opts = "horgai"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(1)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-r', '--followers'):
            options['followers'] = True
        elif opt in ('-g', '--following'):
            options['followers'] = False
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-i', '--ids'):
            options['show_id'] = True

    options['extra_args'] = extra_args 
Example 16
Project: aws-support-tools   Author: awslabs   File: qi.py    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 17
Project: SecureTea   Author: owasp-id   File: follow.py    MIT License 6 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'followers', 'following', 'api-rate', 'ids']
    short_opts = "horgai"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(1)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-r', '--followers'):
            options['followers'] = True
        elif opt in ('-g', '--following'):
            options['followers'] = False
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-i', '--ids'):
            options['show_id'] = True

    options['extra_args'] = extra_args 
Example 18
Project: script.module.twitter   Author: enen92   File: follow.py    MIT License 6 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'followers', 'following', 'api-rate', 'ids']
    short_opts = "horgai"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(1)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-r', '--followers'):
            options['followers'] = True
        elif opt in ('-g', '--following'):
            options['followers'] = False
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-i', '--ids'):
            options['show_id'] = True

    options['extra_args'] = extra_args 
Example 19
Project: python-for-android   Author: kuri65536   File: twitter-to-xhtml.py    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 20
Project: Project-New-Reign---Nemesis-Main   Author: ShikyoKira   File: test_getopt.py    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 21
Project: cells   Author: AlesTsurko   File: test_getopt.py    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 22
Project: rocker   Author: mreithub   File: rocker.py    Apache License 2.0 5 votes vote down vote up
def getopt(self):
		try:
			opts, args = getopt.gnu_getopt(sys.argv[1:], 'v')

			for opt,_ in opts:
				if opt == '-v':
					self._verbosity += 1

			return args
		except getopt.GetoptError as e:
			self.error(e, exitCode=1) 
Example 23
Project: mlab-ns   Author: m-lab   File: gflags.py    Apache License 2.0 5 votes vote down vote up
def UseGnuGetOpt(self, use_gnu_getopt=True):
    """Use GNU-style scanning. Allows mixing of flag and non-flag arguments.

    See http://docs.python.org/library/getopt.html#getopt.gnu_getopt

    Args:
      use_gnu_getopt: wether or not to use GNU style scanning.
    """
    self.__dict__['__use_gnu_getopt'] = use_gnu_getopt 
Example 24
Project: eden   Author: facebookexperimental   File: pycompat.py    GNU General Public License v2.0 5 votes vote down vote up
def gnugetoptb(args, shortlist, namelist):
    return _getoptbwrapper(getopt.gnu_getopt, args, shortlist, namelist) 
Example 25
Project: vlcp   Author: hubo1016   File: script.py    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 26
Project: ipv6-hosts   Author: hujy23   File: update_hosts.py    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 27
Project: gmail-backup-com   Author: terry10   File: extractors.py    GNU General Public License v3.0 5 votes vote down vote up
def extract(self, state):
        source = self.getSource()
        if source is None:
            source = sys.argv[1:]

        short = self._getoptShort()
        long = self._getoptLong()

        options, positional = getopt(source, short, long)

        self._extractGetoptOpt(state, options)
        self._extractGetoptPos(state, positional) 
Example 28
Project: honeything   Author: omererdem   File: options.py    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 29
Project: customs   Author: Mnkai   File: customs.py    GNU General Public License v3.0 5 votes vote down vote up
def main(argv):
    hbl = ''
    year = ''

    try:
        if len(argv) == 0:
            raise getopt.GetoptError
        opts, args = getopt.gnu_getopt(argv, "hb:y:", ["help", "hbl=", "year="])
    except getopt.GetoptError:
        print("Usage: customs.py -b <H B/L> -y <year - optional>\n"
              "\n"
              "-b, --hbl: H B/L\n"
              "-y, --year: Year (optional), defaults to this year\n"
              "-h, --help: Shows help\n")
        sys.exit(1)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            print("Usage: customs.py -b <H B/L> -y <year - optional>\n"
                  "\n"
                  "-b, --hbl: H B/L\n"
                  "-y, --year: Year (optional), defaults to this year\n"
                  "-h, --help: Shows help\n")
            sys.exit()
        elif opt in ("-b", "--hbl"):
            hbl = arg
        elif opt in ("-y", "--year"):
            year = arg

    if year == "":
        year = str(datetime.datetime.now().year)

    summary_json = get_summary_info(hbl, year)
    summary_decoded = json.loads(summary_json)

    # TODO: Dynamically search from dict without hard coding the path
    cargo_management_number = summary_decoded['resultList'][0]['cargMtNo']

    detail_json = get_detailed_info(cargo_management_number)
    detail_decoded = json.loads(detail_json)

    display_info(detail_decoded) 
Example 30
Project: RMIT-Assignment   Author: SpZanG   File: assign1TestScript.py    GNU General Public License v3.0 5 votes vote down vote up
def main():

    # process command line arguments
    try:
        # option list
        sOptions = "v"
        # get options
        optList, remainArgs = getopt.gnu_getopt(sys.argv[1:], sOptions)
    except getopt.GetoptError, err:
        print >> sys.stderr, str(err)
        usage(sys.argv[0]) 
Example 31
Project: RMIT-Assignment   Author: SpZanG   File: assign1TestScript.py    GNU General Public License v3.0 5 votes vote down vote up
def main():

    # process command line arguments
    try:
        # option list
        sOptions = "v"
        # get options
        optList, remainArgs = getopt.gnu_getopt(sys.argv[1:], sOptions)
    except getopt.GetoptError, err:
        print >> sys.stderr, str(err)
        usage(sys.argv[0]) 
Example 32
Project: painter-goblin   Author: ross-spencer   File: cmdline.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_args(args, options):
    long_opts = ['help', 'format=', 'refresh', 'oauth=',
                 'refresh-rate=', 'config=', 'length=', 'timestamp',
                 'datestamp', 'no-ssl', 'force-ansi']
    short_opts = "e:p:f:h?rR:c:l:td"
    opts, extra_args = getopt(args, short_opts, long_opts)
    if extra_args and hasattr(extra_args[0], 'decode'):
        extra_args = [arg.decode(locale.getpreferredencoding())
                      for arg in extra_args]

    for opt, arg in opts:
        if opt in ('-f', '--format'):
            options['format'] = arg
        elif opt in ('-r', '--refresh'):
            options['refresh'] = True
        elif opt in ('-R', '--refresh-rate'):
            options['refresh_rate'] = int(arg)
        elif opt in ('-l', '--length'):
            options["length"] = int(arg)
        elif opt in ('-t', '--timestamp'):
            options["timestamp"] = True
        elif opt in ('-d', '--datestamp'):
            options["datestamp"] = True
        elif opt in ('-?', '-h', '--help'):
            options['action'] = 'help'
        elif opt in ('-c', '--config'):
            options['config_filename'] = arg
        elif opt == '--no-ssl':
            options['secure'] = False
        elif opt == '--oauth':
            options['oauth_filename'] = arg
        elif opt == '--force-ansi':
            options['force-ansi'] = True

    if extra_args and not ('action' in options and options['action'] == 'help'):
        options['action'] = extra_args[0]
    options['extra_args'] = extra_args[1:] 
Example 33
Project: painter-goblin   Author: ross-spencer   File: archiver.py    GNU General Public License v3.0 5 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'save-dir=', 'api-rate', 'timeline=', 'mentions=', 'favorites', 'follow-redirects',"redirect-sites=", 'dms=', 'isoformat']
    short_opts = "hos:at:m:vfr:d:i"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(0)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-s', '--save-dir'):
            options['save-dir'] = arg
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-t', '--timeline'):
            options['timeline'] = arg
        elif opt in ('-m', '--mentions'):
            options['mentions'] = arg
        elif opt in ('-v', '--favorites'):
            options['favorites'] = True
        elif opt in ('-f', '--follow-redirects'):
            options['follow-redirects'] = True
        elif opt in ('-r', '--redirect-sites'):
            options['redirect-sites'] = arg
        elif opt in ('-d', '--dms'):
            options['dms'] = arg
        elif opt in ('-i', '--isoformat'):
            options['isoformat'] = True

    options['extra_args'] = extra_args 
Example 34
Project: SecureTea   Author: owasp-id   File: cmdline.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    long_opts = ['help', 'format=', 'refresh', 'oauth=',
                 'refresh-rate=', 'config=', 'length=', 'timestamp',
                 'datestamp', 'no-ssl', 'force-ansi']
    short_opts = "e:p:f:h?rR:c:l:td"
    opts, extra_args = getopt(args, short_opts, long_opts)
    if extra_args and hasattr(extra_args[0], 'decode'):
        extra_args = [arg.decode(locale.getpreferredencoding())
                      for arg in extra_args]

    for opt, arg in opts:
        if opt in ('-f', '--format'):
            options['format'] = arg
        elif opt in ('-r', '--refresh'):
            options['refresh'] = True
        elif opt in ('-R', '--refresh-rate'):
            options['refresh_rate'] = int(arg)
        elif opt in ('-l', '--length'):
            options["length"] = int(arg)
        elif opt in ('-t', '--timestamp'):
            options["timestamp"] = True
        elif opt in ('-d', '--datestamp'):
            options["datestamp"] = True
        elif opt in ('-?', '-h', '--help'):
            options['action'] = 'help'
        elif opt in ('-c', '--config'):
            options['config_filename'] = arg
        elif opt == '--no-ssl':
            options['secure'] = False
        elif opt == '--oauth':
            options['oauth_filename'] = arg
        elif opt == '--force-ansi':
            options['force-ansi'] = True

    if extra_args and not ('action' in options and options['action'] == 'help'):
        options['action'] = extra_args[0]
    options['extra_args'] = extra_args[1:] 
Example 35
Project: SecureTea   Author: owasp-id   File: archiver.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'save-dir=', 'api-rate', 'timeline=', 'mentions=', 'favorites', 'follow-redirects',"redirect-sites=", 'dms=', 'isoformat']
    short_opts = "hos:at:m:vfr:d:i"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(0)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-s', '--save-dir'):
            options['save-dir'] = arg
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-t', '--timeline'):
            options['timeline'] = arg
        elif opt in ('-m', '--mentions'):
            options['mentions'] = arg
        elif opt in ('-v', '--favorites'):
            options['favorites'] = True
        elif opt in ('-f', '--follow-redirects'):
            options['follow-redirects'] = True
        elif opt in ('-r', '--redirect-sites'):
            options['redirect-sites'] = arg
        elif opt in ('-d', '--dms'):
            options['dms'] = arg
        elif opt in ('-i', '--isoformat'):
            options['isoformat'] = True

    options['extra_args'] = extra_args 
Example 36
Project: SecureTea   Author: owasp-id   File: cmdline.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    long_opts = ['help', 'format=', 'refresh', 'oauth=',
                 'refresh-rate=', 'config=', 'length=', 'timestamp',
                 'datestamp', 'no-ssl', 'force-ansi']
    short_opts = "e:p:f:h?rR:c:l:td"
    opts, extra_args = getopt(args, short_opts, long_opts)
    if extra_args and hasattr(extra_args[0], 'decode'):
        extra_args = [arg.decode(locale.getpreferredencoding())
                      for arg in extra_args]

    for opt, arg in opts:
        if opt in ('-f', '--format'):
            options['format'] = arg
        elif opt in ('-r', '--refresh'):
            options['refresh'] = True
        elif opt in ('-R', '--refresh-rate'):
            options['refresh_rate'] = int(arg)
        elif opt in ('-l', '--length'):
            options["length"] = int(arg)
        elif opt in ('-t', '--timestamp'):
            options["timestamp"] = True
        elif opt in ('-d', '--datestamp'):
            options["datestamp"] = True
        elif opt in ('-?', '-h', '--help'):
            options['action'] = 'help'
        elif opt in ('-c', '--config'):
            options['config_filename'] = arg
        elif opt == '--no-ssl':
            options['secure'] = False
        elif opt == '--oauth':
            options['oauth_filename'] = arg
        elif opt == '--force-ansi':
            options['force-ansi'] = True

    if extra_args and not ('action' in options and options['action'] == 'help'):
        options['action'] = extra_args[0]
    options['extra_args'] = extra_args[1:] 
Example 37
Project: SecureTea   Author: owasp-id   File: archiver.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'save-dir=', 'api-rate', 'timeline=', 'mentions=', 'favorites', 'follow-redirects',"redirect-sites=", 'dms=', 'isoformat']
    short_opts = "hos:at:m:vfr:d:i"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(0)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-s', '--save-dir'):
            options['save-dir'] = arg
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-t', '--timeline'):
            options['timeline'] = arg
        elif opt in ('-m', '--mentions'):
            options['mentions'] = arg
        elif opt in ('-v', '--favorites'):
            options['favorites'] = True
        elif opt in ('-f', '--follow-redirects'):
            options['follow-redirects'] = True
        elif opt in ('-r', '--redirect-sites'):
            options['redirect-sites'] = arg
        elif opt in ('-d', '--dms'):
            options['dms'] = arg
        elif opt in ('-i', '--isoformat'):
            options['isoformat'] = True

    options['extra_args'] = extra_args 
Example 38
Project: script.module.twitter   Author: enen92   File: cmdline.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    long_opts = ['help', 'format=', 'refresh', 'oauth=',
                 'refresh-rate=', 'config=', 'length=', 'timestamp',
                 'datestamp', 'no-ssl', 'force-ansi']
    short_opts = "e:p:f:h?rR:c:l:td"
    opts, extra_args = getopt(args, short_opts, long_opts)
    if extra_args and hasattr(extra_args[0], 'decode'):
        extra_args = [arg.decode(locale.getpreferredencoding())
                      for arg in extra_args]

    for opt, arg in opts:
        if opt in ('-f', '--format'):
            options['format'] = arg
        elif opt in ('-r', '--refresh'):
            options['refresh'] = True
        elif opt in ('-R', '--refresh-rate'):
            options['refresh_rate'] = int(arg)
        elif opt in ('-l', '--length'):
            options["length"] = int(arg)
        elif opt in ('-t', '--timestamp'):
            options["timestamp"] = True
        elif opt in ('-d', '--datestamp'):
            options["datestamp"] = True
        elif opt in ('-?', '-h', '--help'):
            options['action'] = 'help'
        elif opt in ('-c', '--config'):
            options['config_filename'] = arg
        elif opt == '--no-ssl':
            options['secure'] = False
        elif opt == '--oauth':
            options['oauth_filename'] = arg
        elif opt == '--force-ansi':
            options['force-ansi'] = True

    if extra_args and not ('action' in options and options['action'] == 'help'):
        options['action'] = extra_args[0]
    options['extra_args'] = extra_args[1:] 
Example 39
Project: script.module.twitter   Author: enen92   File: archiver.py    MIT License 5 votes vote down vote up
def parse_args(args, options):
    """Parse arguments from command-line to set options."""
    long_opts = ['help', 'oauth', 'save-dir=', 'api-rate', 'timeline=', 'mentions=', 'favorites', 'follow-redirects',"redirect-sites=", 'dms=', 'isoformat']
    short_opts = "hos:at:m:vfr:d:i"
    opts, extra_args = getopt(args, short_opts, long_opts)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(__doc__)
            raise SystemExit(0)
        elif opt in ('-o', '--oauth'):
            options['oauth'] = True
        elif opt in ('-s', '--save-dir'):
            options['save-dir'] = arg
        elif opt in ('-a', '--api-rate'):
            options['api-rate' ] = True
        elif opt in ('-t', '--timeline'):
            options['timeline'] = arg
        elif opt in ('-m', '--mentions'):
            options['mentions'] = arg
        elif opt in ('-v', '--favorites'):
            options['favorites'] = True
        elif opt in ('-f', '--follow-redirects'):
            options['follow-redirects'] = True
        elif opt in ('-r', '--redirect-sites'):
            options['redirect-sites'] = arg
        elif opt in ('-d', '--dms'):
            options['dms'] = arg
        elif opt in ('-i', '--isoformat'):
            options['isoformat'] = True

    options['extra_args'] = extra_args 
Example 40
Project: python-for-android   Author: kuri65536   File: tweet.py    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 41
Project: verifierad   Author: Vastra-Gotalandsregionen   File: __init__.py    MIT License 5 votes vote down vote up
def main():
	shortoptions = 'hL:'
	options = 'help csv lang= tokenizer='.split()
	cmd = os.path.basename(sys.argv[0])
	usage = __doc__ % dict(cmd=cmd, lang=', '.join(LANGDATA))
	try:
		opts, args = getopt.gnu_getopt(sys.argv[1:], shortoptions, options)
	except getopt.GetoptError as err:
		print('error: %r\n%s' % (err, usage))
		sys.exit(2)
	opts = dict(opts)
	lang = opts.get('--lang', opts.get('-L', 'en'))

	if '--help' in opts or '-h' in opts:
		print(usage)
		return
	elif '--csv' in opts:
		result = getdataframe(args, lang=lang,
				tokenizer=opts.get('--tokenizer'))
		result.to_csv(sys.stdout)
		return
	elif len(args) == 0 or args == ['-']:
		text = io.TextIOWrapper(sys.stdin.buffer, encoding='utf8')
	elif len(args) == 1:
		text = applytokenizer(args[0], opts.get('--tokenizer'), 'utf8')
	else:
		raise ValueError('expected 0 or 1 file argument.')
	try:
		for cat, data in getmeasures(text, lang).items():
			print('%s:' % cat)
			for key, val in data.items():
				print(('    %-25s %12.2f' % (key + ':', val)
						).rstrip('0 ').rstrip('.'))
	except KeyboardInterrupt:
		sys.exit(1) 
Example 42
Project: guth   Author: bjarneh   File: guth.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def niceopt(argv, short_opts, long_opts):
    """ Allow long options which start with a single '-' sign"""
    for i, e in enumerate(argv):
        for opt in long_opts:
            if( e.startswith("-" + opt) or
              ( e.startswith("-" + opt[:-1]) and opt[-1] == "=") ):
                argv[i] = "-" + e
    return getopt.gnu_getopt(argv, short_opts, long_opts) 
Example 43
Project: dogbot   Author: moondropx   File: poster.py    Apache License 2.0 4 votes vote down vote up
def poster(bot, message):
    """#poster [-h] [-f]

    -h : 打印本帮助
    -f : 强制刷新
    """

    try:
        cmd, *args = shlex.split(message.text)
    except ValueError:
        return False
    if not cmd[0] in config['trigger']:
        return False
    if not cmd[1:] == 'poster':
        return False
    try:
        options, args = getopt.gnu_getopt(args, 'hf')
    except getopt.GetoptError:
        # 格式不对
        reply(bot, message, poster.__doc__)
        return True

    refresh = False

    # 拆参数
    for o, a in options:
        if o == '-h':
            # 帮助
            reply(bot, message, poster.__doc__)
            return True
        elif o == '-f':
            refresh = True

    weekday = datetime.now().weekday()
    if weekday >= 3:
        delta = timedelta(days=weekday-3)
    else:
        delta = timedelta(days=7+weekday-3)

    thu_date = datetime.now().date() - delta
    url = '{}event{}.jpg'.format(BASE_URL, thu_date.strftime('%Y%m%d'))
    filename = os.path.basename(url)
    dir = os.path.join(config['cq_root_dir'], config['cq_image_dir'], 'poster')
    path = os.path.join(dir, filename)

    if not os.path.exists(dir):
        os.mkdir(dir)

    if not os.path.exists(path) or refresh:
        resp = requests.get(url, timeout=60, proxies=config.get('proxies'))
        if not resp.status_code == 200:
            reply(bot, message, '没找到海报...还没更新或者是网络问题?')
            return True
        # 压缩图片
        img = Image.open(io.BytesIO(resp.content))
        img.save(path, quality=40)
        # with open(path, 'wb') as f:
        #     f.write(resp.content)

    reply(bot, message, CQImage(os.path.join('poster', filename)))
    return True 
Example 44
Project: dogbot   Author: moondropx   File: emoji.py    Apache License 2.0 4 votes vote down vote up
def emoji_lock(bot, message):
    """#emoji_lock [-d 名称] 等级

    -d 名称 : 要操作的emoji的名称
    等级    : 锁定等级,0为不锁定,1为不允许删除,2为不允许删除&添加。
    """
    try:
        cmd, *args = shlex.split(message.text)
    except ValueError:
        return False
    if not cmd[0] in config['trigger']:
        return False
    if not cmd[1:] == 'emoji_lock':
        return False
    
    if message.qq not in config['admins']:
        reply(bot, message, '没有权限!')
        return True

    try:
        options, args = getopt.gnu_getopt(args, 'hd:')
    except getopt.GetoptError:
        # 格式不对
        reply(bot, message, emoji_alias.__doc__)
        return True

    if len(args) < 1:
        reply(bot, message, '没输入等级...')
        return True

    level = int(args[0])
    if level not in [0, 1, 2]:
        reply(bot, message, '等级有误...')
        return True

    name = None

    for o, a in options:
        if o == '-d':
            name = a
        elif o == '-h':
            # 帮助
            reply(bot, message, emoji_alias.__doc__)
            return True

    if not name:
        reply(bot, message, emoji_alias.__doc__)
        return True

    emoji = Emoji.objects(name=name).first()
    if not emoji:
        reply(bot, message, '找不到名称{}'.format(name))
        return True

    emoji.lock = level
    emoji.save()
    reply(bot, message, 'emoji[{}]现在为锁定等级{}'.format(name, level))
    return True 
Example 45
Project: dogbot   Author: moondropx   File: helper.py    Apache License 2.0 4 votes vote down vote up
def unalias_command(bot, message):
    """#unalias [-h] 命令

    -h  : 打印本帮助
    命令 : 要删除的别名
    """

    try:
        cmd, *args = shlex.split(message.text)
    except ValueError:
        return False
    if not cmd[0] in config['trigger']:
        return False
    if not cmd[1:] == 'unalias':
        return False
    try:
        options, args = getopt.gnu_getopt(args, 'hd:')
    except getopt.GetoptError:
        # 格式不对
        reply(bot, message, unalias_command.__doc__)
        return True

    origin = None

    for o, a in options:
        if o == '-h':
            # 帮助
            reply(bot, message, unalias_command.__doc__)
            return True

    # 一定要有命令
    if not args:
        reply(bot, message, unalias_command.__doc__)
        return True

    command = args[0]
    alias = Alias.objects(alias=command)

    if not alias:
        reply(bot, message, '没找到别名{}'.format(command))

    reply(bot, message, '删掉了别名 {} => {}'.format(alias.alias, alias.origin))
    alias.delete()
    return True 
Example 46
Project: dogbot   Author: moondropx   File: twitter.py    Apache License 2.0 4 votes vote down vote up
def twitter(bot, message):
    """#twitter [-p 天数]

    -p : 几天以前
    """

    try:
        cmd, *args = shlex.split(message.text)
    except ValueError:
        return False
    if not cmd[0] in config['trigger']:
        return False
    if not cmd[1:] == 'twitter':
        return False
    try:
        options, args = getopt.gnu_getopt(args, 'hp:')
    except getopt.GetoptError:
        # 格式不对
        reply(bot, message, twitter.__doc__)
        return True

    days = 0
    for o, a in options:
        if o == '-p':
            # 几天以前
            try:
                days = int(a)
                if days < 0:
                    raise ValueError
            except ValueError:
                reply(bot, message, twitter.__doc__)
                return True
        elif o == '-h':
            # 帮助
            reply(bot, message, twitter.__doc__)
            return True
    tweets = Twitter.objects(Q(date__gte=datetime.now().date()+timedelta(days=-days)) & Q(date__lte=datetime.now().date()+timedelta(days=-days+1)))

    if tweets:
        reply(bot, message, '\n---------\n'.join([str(tweet) for tweet in tweets]))
        return True
    else:
        reply(bot, message, '安娜啥都没说...')
        return True 
Example 47
Project: dotfiles   Author: butlerx   File: grep.py    MIT License 4 votes vote down vote up
def cmd_logs(data, buffer, args):
    """List files in Weechat's log dir."""
    cmd_init()
    global home_dir
    sort_by_size = False
    filter = []

    try:
        opts, args = getopt.gnu_getopt(args.split(), 's', ['size'])
        if args:
            filter = args
        for opt, var in opts:
            opt = opt.strip('-')
            if opt in ('size', 's'):
                sort_by_size = True
    except Exception as e:
        error('Argument error, %s' % e)
        return WEECHAT_RC_OK

    # is there's a filter, filter_excludes should be False
    file_list = dir_list(home_dir, filter, filter_excludes=not filter)
    if sort_by_size:
        file_list.sort(key=get_size)
    else:
        file_list.sort()

    file_sizes = map(lambda x: human_readable_size(get_size(x)), file_list)
    # calculate column lenght
    if file_list:
        L = file_list[:]
        L.sort(key=len)
        bigest = L[-1]
        column_len = len(bigest) + 3
    else:
        column_len = ''

    buffer = buffer_create()
    if get_config_boolean('clear_buffer'):
        weechat.buffer_clear(buffer)
    file_list = zip(file_list, file_sizes)
    msg = 'Found %s logs.' %len(file_list)

    print_line(msg, buffer, display=True)
    for file, size in file_list:
        separator = column_len and '.'*(column_len - len(file))
        prnt(buffer, '%s %s %s' %(strip_home(file), separator, size))
    if file_list:
        print_line(msg, buffer)
    return WEECHAT_RC_OK


### Completion ### 
Example 48
Project: dotfiles   Author: butlerx   File: grep.py    MIT License 4 votes vote down vote up
def cmd_logs(data, buffer, args):
    """List files in Weechat's log dir."""
    cmd_init()
    global home_dir
    sort_by_size = False
    filter = []

    try:
        opts, args = getopt.gnu_getopt(args.split(), 's', ['size'])
        if args:
            filter = args
        for opt, var in opts:
            opt = opt.strip('-')
            if opt in ('size', 's'):
                sort_by_size = True
    except Exception as e:
        error('Argument error, %s' % e)
        return WEECHAT_RC_OK

    # is there's a filter, filter_excludes should be False
    file_list = dir_list(home_dir, filter, filter_excludes=not filter)
    if sort_by_size:
        file_list.sort(key=get_size)
    else:
        file_list.sort()

    file_sizes = map(lambda x: human_readable_size(get_size(x)), file_list)
    # calculate column lenght
    if file_list:
        L = file_list[:]
        L.sort(key=len)
        bigest = L[-1]
        column_len = len(bigest) + 3
    else:
        column_len = ''

    buffer = buffer_create()
    if get_config_boolean('clear_buffer'):
        weechat.buffer_clear(buffer)
    file_list = zip(file_list, file_sizes)
    msg = 'Found %s logs.' %len(file_list)

    print_line(msg, buffer, display=True)
    for file, size in file_list:
        separator = column_len and '.'*(column_len - len(file))
        prnt(buffer, '%s %s %s' %(strip_home(file), separator, size))
    if file_list:
        print_line(msg, buffer)
    return WEECHAT_RC_OK


### Completion ### 
Example 49
Project: zipbomb-generator   Author: CreeperKong   File: zipbomb.py    GNU General Public License v3.0 4 votes vote down vote up
def main():
    opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ["algorithm=", "alphabet=", "compressed-size=", "extra=", "help", "max-uncompressed-size=", "mode=", "num-files=", "template=", "zip64"])
    assert not args, args
    global FILENAME_ALPHABET
    mode = write_zip_quoted_overlap
    compression_method = COMPRESSION_METHOD_DEFLATE
    compressed_size = None
    max_uncompressed_size = None
    extra_tag = None
    template_filenames = []
    zip64 = False
    for o, a in opts:
        if o == "--algorithm":
            compression_method = {
                "bzip2": COMPRESSION_METHOD_BZIP2,
                "deflate": COMPRESSION_METHOD_DEFLATE,
            }[a]
        elif o == "--alphabet":
            assert len(set(sorted(a))) == len(a), a
            FILENAME_ALPHABET = bytes(a, "utf-8")
        elif o == "--compressed-size":
            compressed_size = int(a)
        elif o == "--extra":
            # This is an experimental feature that quotes as many files as
            # possible inside the Extra Field of local file headers, rather than
            # quoting using DEFLATE non-compressed blocks. The argument is a
            # 16-bit hexadecimal tag ID. It should be possible to use any tag ID
            # that's unallocated in APPNOTE.TXT 4.5.2.
            extra_tag = int(a, 16)
        elif o == "--max-uncompressed-size":
            max_uncompressed_size = int(a)
        elif o == "--mode":
            mode = {
                "no_overlap": write_zip_no_overlap,
                "full_overlap": write_zip_full_overlap,
                "quoted_overlap": write_zip_quoted_overlap,
            }[a]
        elif o == "--num-files":
            num_files = int(a)
        elif o == "--template":
            template_filenames.append(a)
        elif o == "--zip64":
            zip64 = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit(1)

    if extra_tag is not None and mode != write_zip_quoted_overlap:
        print("--extra only makes sense with --mode=quoted_overlap", file=sys.stderr)
        sys.exit(1)

    template = []
    for filename in template_filenames:
        template.extend(load_template(filename))

    mode(sys.stdout.buffer, num_files, compressed_size=compressed_size, max_uncompressed_size=max_uncompressed_size, compression_method=compression_method, zip64=zip64, template=template, extra_tag=extra_tag) 
Example 50
Project: cutlass   Author: ihmpdcc   File: generate_pass.py    MIT License 4 votes vote down vote up
def main(argv):
    """The main body of execution."""

    username = None
    password = None

    try:
        opts, args = getopt.gnu_getopt(argv, "u:ph",
                                       ["username=", "password", "help"])
        if not opts:
            how_to()
            sys.exit(2)
    except getopt.GetoptError as err:
        print err
        how_to()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-u", "--username"):
            username = arg
        elif opt in ("-p", "--password"):
            password = getpass.getpass("Enter your password:")
        elif opt in ("-h", "--help"):
            how_to()
            sys.exit(2)

    if password is None:
        password = getpass.getpass(
            "Enter your password (Don't worry, it's not shown): "
        )
        password_confirm = getpass.getpass(
            "Enter your password AGAIN to confirm: "
        )

    if password != password_confirm:
        print("Passwords entered do not match.")
        sys.exit(1)

    sha1 = get_sha1_hash(password)

    salted_hash = generate_password_hash(password, method='sha1')

    print("="*80)
    print("SHA1:        %s" % sha1)
    print("Salted SHA1: %s:%s" % (username, salted_hash)) 
Example 51
Project: bls_sigs_ref-archive   Author: kwantam   File: util.py    Apache License 2.0 4 votes vote down vote up
def get_cmdline_options():
    sk = "11223344556677889900112233445566"
    msg_dflt = "the message to be signed"
    ret = []
    sig_type = "NUL"

    # go through the commandline arguments
    try:
        (opts, args) = getopt.gnu_getopt(sys.argv[1:], "k:dgT:BAP")

    except getopt.GetoptError as err:
        print "Usage: %s [-B | -A | -P] [-g] [-d] [-k key] [-T test_file] [msg ...]" % sys.argv[0]
        sys.exit(str(err))

    for (opt, arg) in opts:
        if opt == "-k":
            sk = arg

        elif opt == "-d":
            enable_debug()

        elif opt == "-g":
            enable_genvec()

        elif opt == "-T":
            with open(arg, "r") as test_file:
                ret += [ tuple( binascii.unhexlify(val) \
                                for val in line.strip().split(' ') ) \
                         for line in test_file.readlines() ]

        elif opt == "-B":
            sig_type = "NUL"

        elif opt == "-A":
            sig_type = "AUG"

        elif opt == "-P":
            sig_type = "POP"

        else:
            raise RuntimeError("got unexpected option %s from getopt" % opt)

    # build up return value: (msg, sk) tuples from cmdline and any test files
    ret += [ (arg, sk) for arg in args ]
    if not ret:
        ret = [ (msg_dflt, sk) ]

    return (sig_type, ret) 
Example 52
Project: bls_sigs_ref-archive   Author: kwantam   File: util.py    Apache License 2.0 4 votes vote down vote up
def get_cmdline_options():
    sk = bytes("11223344556677889900112233445566", "ascii")
    msg_dflt = bytes("the message to be signed", "ascii")
    ret = Options()

    # process cmdline args with getopt
    try:
        (opts, args) = getopt.gnu_getopt(sys.argv[1:], "k:T:tvqBAPg")

    except getopt.GetoptError as err:
        print("Usage: %s [-gqtv] [-k key] [-T test_file] [-B | -A | -P] [msg ...]" % sys.argv[0])
        sys.exit(str(err))

    for (opt, arg) in opts:
        if opt == "-k":
            sk = os.fsencode(arg)

        elif opt == "-T":
            ret.test_inputs += _read_test_file(arg)

        elif opt == "-t":
            ret.run_tests = True

        elif opt == "-v":
            ret.verify = True

        elif opt == "-q":
            ret.quiet = True

        elif opt == "-B":
            ret.sigtype = SigType.basic

        elif opt == "-A":
            ret.sigtype = SigType.message_augmentation

        elif opt == "-P":
            ret.sigtype = SigType.proof_of_possession

        elif opt == "-g":
            ret.gen_vectors = True

        else:
            raise RuntimeError("got unexpected option %s from getopt" % opt)

    # build up return value: (msg, sk) tuples from cmdline and test files
    ret.test_inputs += [ (os.fsencode(arg), sk) for arg in args ]
    if not ret.test_inputs:
        ret.test_inputs = [ (msg_dflt, sk) ]

    return ret 
Example 53
Project: bls_sigs_ref   Author: algorand   File: util.py    MIT License 4 votes vote down vote up
def get_cmdline_options():
    sk = "11223344556677889900112233445566"
    msg_dflt = "the message to be signed"
    ret = []
    sig_type = "NUL"

    # go through the commandline arguments
    try:
        (opts, args) = getopt.gnu_getopt(sys.argv[1:], "k:dgT:BAP")

    except getopt.GetoptError as err:
        print "Usage: %s [-B | -A | -P] [-g] [-d] [-k key] [-T test_file] [msg ...]" % sys.argv[0]
        sys.exit(str(err))

    for (opt, arg) in opts:
        if opt == "-k":
            sk = arg

        elif opt == "-d":
            enable_debug()

        elif opt == "-g":
            enable_genvec()

        elif opt == "-T":
            with open(arg, "r") as test_file:
                ret += [ tuple( binascii.unhexlify(val) \
                                for val in line.strip().split(' ') ) \
                         for line in test_file.readlines() ]

        elif opt == "-B":
            sig_type = "NUL"

        elif opt == "-A":
            sig_type = "AUG"

        elif opt == "-P":
            sig_type = "POP"

        else:
            raise RuntimeError("got unexpected option %s from getopt" % opt)

    # build up return value: (msg, sk) tuples from cmdline and any test files
    ret += [ (arg, sk) for arg in args ]
    if not ret:
        ret = [ (msg_dflt, sk) ]

    return (sig_type, ret) 
Example 54
Project: bls_sigs_ref   Author: algorand   File: util.py    MIT License 4 votes vote down vote up
def get_cmdline_options():
    sk = bytes("11223344556677889900112233445566", "ascii")
    msg_dflt = bytes("the message to be signed", "ascii")
    ret = Options()

    # process cmdline args with getopt
    try:
        (opts, args) = getopt.gnu_getopt(sys.argv[1:], "k:T:tvqBAPg")

    except getopt.GetoptError as err:
        print("Usage: %s [-gqtv] [-k key] [-T test_file] [-B | -A | -P] [msg ...]" % sys.argv[0])
        sys.exit(str(err))

    for (opt, arg) in opts:
        if opt == "-k":
            sk = os.fsencode(arg)

        elif opt == "-T":
            ret.test_inputs += _read_test_file(arg)

        elif opt == "-t":
            ret.run_tests = True

        elif opt == "-v":
            ret.verify = True

        elif opt == "-q":
            ret.quiet = True

        elif opt == "-B":
            ret.sigtype = SigType.basic

        elif opt == "-A":
            ret.sigtype = SigType.message_augmentation

        elif opt == "-P":
            ret.sigtype = SigType.proof_of_possession

        elif opt == "-g":
            ret.gen_vectors = True

        else:
            raise RuntimeError("got unexpected option %s from getopt" % opt)

    # build up return value: (msg, sk) tuples from cmdline and test files
    ret.test_inputs += [ (os.fsencode(arg), sk) for arg in args ]
    if not ret.test_inputs:
        ret.test_inputs = [ (msg_dflt, sk) ]

    return ret 
Example 55
Project: broc   Author: baidu   File: Options.py    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