Python getopt.getopt() Examples

The following are code examples for showing how to use getopt.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: trace.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def main(argv=None):
    import getopt

    if argv is None:
        argv = sys.argv
    try:
        opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
                                        ["help", "version", "trace", "count",
                                         "report", "no-report", "summary",
                                         "file=", "missing",
                                         "ignore-module=", "ignore-dir=",
                                         "coverdir=", "listfuncs",
                                         "trackcalls", "timing"])

    except getopt.error, msg:
        sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
        sys.stderr.write("Try `%s --help' for more information\n"
                         % sys.argv[0])
        sys.exit(1) 
Example 2
Project: zabbix   Author: xiaomatech   File: getZookeeperInfo.py    MIT License 7 votes vote down vote up
def main(host, port, zkCommand, zkKey):

    try:
        options, args = getopt.getopt(
            sys.argv[1:], "h:p:c:k:",
            ["host=", "port=", "zkCommand=", "zkKey="])
        for name, value in options:
            if name in ('-h', '--host'):
                host = value
            if name in ('-p', '--port'):
                port = value
            if name in ('-c', '--zkCommand'):
                zkCommand = value
            if name in ('-k', '--zkKey'):
                zkKey = value
    except getopt.GetoptError, err:
        print str(err)
        Usage()
        sys.exit(1) 
Example 3
Project: pyblish-win   Author: pyblish   File: webchecker.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    checkext = CHECKEXT
    verbose = VERBOSE
    maxpage = MAXPAGE
    roundsize = ROUNDSIZE
    dumpfile = DUMPFILE
    restart = 0
    norun = 0

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'Rd:m:nqr:t:vxa')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print __doc__%globals()
        sys.exit(2)

    # The extra_roots variable collects extra roots. 
Example 4
Project: pyblish-win   Author: pyblish   File: rgrep.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    bufsize = 64*1024
    reflags = 0
    opts, args = getopt.getopt(sys.argv[1:], "i")
    for o, a in opts:
        if o == '-i':
            reflags = reflags | re.IGNORECASE
    if len(args) < 2:
        usage("not enough arguments")
    if len(args) > 2:
        usage("exactly one file argument required")
    pattern, filename = args
    try:
        prog = re.compile(pattern, reflags)
    except re.error, msg:
        usage("error in regular expression: %s" % str(msg)) 
Example 5
Project: pyblish-win   Author: pyblish   File: ifdef.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
    for o, a in opts:
        if o == '-D':
            defs.append(a)
        if o == '-U':
            undefs.append(a)
    if not args:
        args = ['-']
    for filename in args:
        if filename == '-':
            process(sys.stdin, sys.stdout)
        else:
            f = open(filename, 'r')
            process(f, sys.stdout)
            f.close() 
Example 6
Project: pyblish-win   Author: pyblish   File: pygettext.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main():
    global default_keywords
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'ad:DEhk:Kno:p:S:Vvw:x:X:',
            ['extract-all', 'default-domain=', 'escape', 'help',
             'keyword=', 'no-default-keywords',
             'add-location', 'no-location', 'output=', 'output-dir=',
             'style=', 'verbose', 'version', 'width=', 'exclude-file=',
             'docstrings', 'no-docstrings',
             ])
    except getopt.error, msg:
        usage(1, msg)

    # for holding option values 
Example 7
Project: pyblish-win   Author: pyblish   File: timeit.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def main(args=None):
    """Main program, used when run as a script.

    The optional argument specifies the command line to be parsed,
    defaulting to sys.argv[1:].

    The return value is an exit code to be passed to sys.exit(); it
    may be None to indicate success.

    When an exception happens during timing, a traceback is printed to
    stderr and the return value is 1.  Exceptions at other times
    (including the template compilation) are not caught.
    """
    if args is None:
        args = sys.argv[1:]
    import getopt
    try:
        opts, args = getopt.getopt(args, "n:s:r:tcvh",
                                   ["number=", "setup=", "repeat=",
                                    "time", "clock", "verbose", "help"])
    except getopt.error, err:
        print err
        print "use -h/--help for command line help"
        return 2 
Example 8
Project: pyblish-win   Author: pyblish   File: rexec.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test():
    import getopt, traceback
    opts, args = getopt.getopt(sys.argv[1:], 'vt:')
    verbose = 0
    trusted = []
    for o, a in opts:
        if o == '-v':
            verbose = verbose+1
        if o == '-t':
            trusted.append(a)
    r = RExec(verbose=verbose)
    if trusted:
        r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
    if args:
        r.modules['sys'].argv = args
        r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
    else:
        r.modules['sys'].path.insert(0, "")
    fp = sys.stdin
    if args and args[0] != '-':
        try:
            fp = open(args[0])
        except IOError, msg:
            print "%s: can't open file %r" % (sys.argv[0], args[0])
            return 1 
Example 9
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_long_has_args(self):
        has_arg, option = getopt.long_has_args('abc', ['abc='])
        self.assertTrue(has_arg)
        self.assertEqual(option, 'abc')

        has_arg, option = getopt.long_has_args('abc', ['abc'])
        self.assertFalse(has_arg)
        self.assertEqual(option, 'abc')

        has_arg, option = getopt.long_has_args('abc', ['abcd'])
        self.assertFalse(has_arg)
        self.assertEqual(option, 'abcd')

        self.assertError(getopt.long_has_args, 'abc', ['def'])
        self.assertError(getopt.long_has_args, 'abc', [])
        self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde']) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_do_shorts(self):
        opts, args = getopt.do_shorts([], 'a', 'a', [])
        self.assertEqual(opts, [('-a', '')])
        self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a1', 'a:', [])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, [])

        #opts, args = getopt.do_shorts([], 'a=1', 'a:', [])
        #self.assertEqual(opts, [('-a', '1')])
        #self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a', 'a:', ['1'])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, [])

        opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2'])
        self.assertEqual(opts, [('-a', '1')])
        self.assertEqual(args, ['2'])

        self.assertError(getopt.do_shorts, [], 'a1', 'a', [])
        self.assertError(getopt.do_shorts, [], 'a', 'a:', []) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_getopt(self):
        # note: the empty string between '-a' and '--beta' is significant:
        # it simulates an empty string option argument ('-a ""') on the
        # command line.
        cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a',
                   '', '--beta', 'arg1', 'arg2']

        opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
        self.assertEqual(opts, [('-a', '1'), ('-b', ''),
                                ('--alpha', '2'), ('--beta', ''),
                                ('-a', '3'), ('-a', ''), ('--beta', '')])
        # Note ambiguity of ('-b', '') and ('-a', '') above. This must be
        # accounted for in the code that calls getopt().
        self.assertEqual(args, ['arg1', 'arg2'])

        self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta']) 
Example 12
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 13
Project: flasky   Author: RoseOu   File: cmdline.py    MIT License 6 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    # pylint: disable-msg=R0911,R0912,R0915

    usage = USAGE % ((args[0],) * 6)

    if sys.platform in ['win32', 'cygwin']:
        try:
            # Provide coloring under Windows, if possible
            import colorama
            colorama.init()
        except ImportError:
            pass

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
    except getopt.GetoptError, err:
        print >>sys.stderr, usage
        return 2 
Example 14
Project: sic   Author: Yanixos   File: base64.py    GNU General Public License v3.0 6 votes vote down vote up
def main():
    """Small main program"""
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'deut')
    except getopt.error as msg:
        sys.stdout = sys.stderr
        print(msg)
        print("""usage: %s [-d|-e|-u|-t] [file|-]
        -d, -u: decode
        -e: encode (default)
        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
        sys.exit(2)
    func = encode
    for o, a in opts:
        if o == '-e': func = encode
        if o == '-d': func = decode
        if o == '-u': func = decode
        if o == '-t': test(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout.buffer)
    else:
        func(sys.stdin.buffer, sys.stdout.buffer) 
Example 15
Project: zabbix   Author: xiaomatech   File: hdfs-collect.py    MIT License 6 votes vote down vote up
def main(argv):
    inputfile, outputfile = "", ""
    help_string = "Usage:\n./%s -i <input_file> -o <output_file>" % (argv[0])
    try:
        opts, args = getopt.getopt(argv[1:], "hi:o:", ["input", "output"])
    except getopt.GetoptError:
        print help_string
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print help_string
            sys.exit()
        elif opt in ("-i", "--input"):
            inputfile = arg
        elif opt in ("-o", "--output"):
            outputfile = arg

    result = scan(inputfile)
    try:
        with open(outputfile, "w") as f:
            f.write(json.dumps(result))
    except IOError:
        print "Error, cant read or write to file '%s'" % outputfile
        sys.exit(2) 
Example 16
Project: Terminal-Pix   Author: Akatsuki06   File: util.py    MIT License 6 votes vote down vote up
def getArgs():
	try: 
		opts, args = getopt.getopt(sys.argv[1:],"f:h:w:",['help'])
	except getopt.GetoptError as e:
		print (str(e))
		print("Usage: %s " % sys.argv[0])
		sys.exit(2)
	file=''
	h=20
	w=20
	for o, a in opts:
		if o=='--help' :
			help()
		if o == '-f':
		   	file=a
		if o == '-h':
		    h=a
		if o =='-w':
			w=a


	return file,h,w 
Example 17
Project: openhatch   Author: campbe13   File: cmdline.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    # pylint: disable-msg=R0911,R0912,R0915

    usage = USAGE % ((args[0],) * 6)

    if sys.platform in ['win32', 'cygwin']:
        try:
            # Provide coloring under Windows, if possible
            import colorama
            colorama.init()
        except ImportError:
            pass

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:hVHg")
    except getopt.GetoptError, err:
        print >>sys.stderr, usage
        return 2 
Example 18
Project: firmanal   Author: kyechou   File: importdb.py    MIT License 6 votes vote down vote up
def main():
    infile = iid = None
    opts, argv = getopt.getopt(sys.argv[1:], "f:i:")
    for k, v in opts:
        if k == '-i':
            iid = int(v)
        if k == '-f':
            infile = v

    if infile and not iid:
        m = re.match(r"(\d+)\.tar\.gz", infile)
        if m:
            iid = int(m.groups(1))

    getarch (infile)
    process(iid, infile) 
Example 19
Project: firmanal   Author: kyechou   File: runExploits.py    MIT License 6 votes vote down vote up
def main():
    exploits = []
    outfile = None
    if len (sys.argv) != 7:
        print ("Usage: ./runExploits.py -t <target-ip> -o <output-dir> -e <exploits>")
        print ("Note: <exploits> can be 'all' or a list of exploits seperated by ','")
        exit (1)
    opts, argv = getopt.getopt(sys.argv[1:], 'e:t:o:')
    for k, v in opts:
        if k == '-e':
            if v == 'all':
                exploits = list (METASPLOIT_EXPLOITS.keys()) + list (SHELL_EXPLOITS.keys())
            else:
                exploits = [int(x) for x in v.split(',')]
        if k == '-t':
            target = v
        if k == '-o':
            if not os.path.isdir(v):
                if os.path.exists(v):
                    os.remove(v)
                os.makedirs(v, 0o755);
            outfile = v + "/%(exploit)s.log"

    process(target, exploits, outfile) 
Example 20
Project: jawfish   Author: war-and-code   File: base64.py    MIT License 6 votes vote down vote up
def main():
    """Small main program"""
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'deut')
    except getopt.error as msg:
        sys.stdout = sys.stderr
        print(msg)
        print("""usage: %s [-d|-e|-u|-t] [file|-]
        -d, -u: decode
        -e: encode (default)
        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
        sys.exit(2)
    func = encode
    for o, a in opts:
        if o == '-e': func = encode
        if o == '-d': func = decode
        if o == '-u': func = decode
        if o == '-t': test(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout.buffer)
    else:
        func(sys.stdin.buffer, sys.stdout.buffer) 
Example 21
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: bitcointalk_sentiment_classifier.py    MIT License 6 votes vote down vote up
def main(argv):
    warnings.filterwarnings('ignore', category=DeprecationWarning)
    input_file = ''
    model_file = ''
    output_folder = ''
    output_posts = ''
    try:
        opts, args = getopt.getopt(argv, "hi:m:f:n:")
    except getopt.GetoptError:
        print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('bitcointalk_sentiment_classifier.py -i <inputfile> -m <model> -f <output folder> -n <number of output posts [number|fraction|all]>')
            sys.exit()
        elif opt == '-i':
            input_file = arg
        elif opt == '-m':
            model_file = arg
        elif opt == '-f':
            output_folder = arg
        elif opt == '-n':
            output_posts = arg

    classify(input_file, model_file, output_folder, output_posts) 
Example 22
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: graph_builder.py    MIT License 6 votes vote down vote up
def main(argv):
    input_file = ''
    save_to = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:")
    except getopt.GetoptError:
        print('graph_builder.py -i <JSON inputfile> -o <output image>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('graph_builder.py -i <JSON inputfile> -o <output image>')
            sys.exit()
        elif opt == '-i':
            input_file = arg
        elif opt == '-o':
            save_to = arg

    build_graph(input_file,save_to) 
Example 23
Project: pyblish-win   Author: pyblish   File: wcgui.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 't:m:qva')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print __doc__%vars(webchecker)
        sys.exit(2) 
Example 24
Project: pyblish-win   Author: pyblish   File: websucker.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    verbose = webchecker.VERBOSE
    try:
        opts, args = getopt.getopt(sys.argv[1:], "qv")
    except getopt.error, msg:
        print msg
        print "usage:", sys.argv[0], "[-qv] ... [rooturl] ..."
        return 2 
Example 25
Project: pyblish-win   Author: pyblish   File: Main.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'hd:i:Xv',
            ['database=', 'initfile=', 'ignore', 'help', 'version'])
    except getopt.error, msg:
        usage(1, msg) 
Example 26
Project: pyblish-win   Author: pyblish   File: reindent.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    import getopt
    global verbose, recurse, dryrun, makebackup
    try:
        opts, args = getopt.getopt(sys.argv[1:], "drnvh",
                        ["dryrun", "recurse", "nobackup", "verbose", "help"])
    except getopt.error, msg:
        usage(msg)
        return 
Example 27
Project: pyblish-win   Author: pyblish   File: ftpmirror.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global verbose, interactive, mac, rmok, nologin
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v')
    except getopt.error, msg:
        usage(msg) 
Example 28
Project: pyblish-win   Author: pyblish   File: logmerge.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    """Main program"""
    truncate_last = 0
    reverse = 0
    branch = None
    opts, args = getopt.getopt(sys.argv[1:], "trb:h")
    for o, a in opts:
        if o == '-t':
            truncate_last = 1
        elif o == '-r':
            reverse = 1
        elif o == '-b':
            branch = a
        elif o == '-h':
            print __doc__
            sys.exit(0)
    database = []
    while 1:
        chunk = read_chunk(sys.stdin)
        if not chunk:
            break
        records = digest_chunk(chunk, branch)
        if truncate_last:
            del records[-1]
        database[len(database):] = records
    database.sort()
    if not reverse:
        database.reverse()
    format_output(database) 
Example 29
Project: pyblish-win   Author: pyblish   File: treesync.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global always_no, always_yes
    global create_directories, write_master, write_slave
    opts, args = getopt.getopt(sys.argv[1:], "nym:s:d:f:a:")
    for o, a in opts:
        if o == '-y':
            default_answer = "yes"
        if o == '-n':
            default_answer = "no"
        if o == '-s':
            write_slave = a
        if o == '-m':
            write_master = a
        if o == '-d':
            create_directories = a
        if o == '-f':
            create_files = a
        if o == '-a':
            create_files = create_directories = write_slave = write_master = a
    try:
        [slave, master] = args
    except ValueError:
        print "usage: python", sys.argv[0] or "treesync.py",
        print "[-n] [-y] [-m y|n|a] [-s y|n|a] [-d y|n|a] [-f n|y|a]",
        print "slavedir masterdir"
        return
    process(slave, master) 
Example 30
Project: pyblish-win   Author: pyblish   File: fixdiv.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hm")
    except getopt.error, msg:
        usage(msg)
        return 2 
Example 31
Project: pyblish-win   Author: pyblish   File: pathfix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global new_interpreter
    usage = ('usage: %s -i /interpreter file-or-directory ...\n' %
             sys.argv[0])
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'i:')
    except getopt.error, msg:
        err(msg + '\n')
        err(usage)
        sys.exit(2) 
Example 32
Project: pyblish-win   Author: pyblish   File: fixnotice.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global DRYRUN, OLD_NOTICE, NEW_NOTICE, VERBOSE
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hv',
                                   ['help', 'oldnotice=', 'newnotice=',
                                    'dry-run', 'verbose'])
    except getopt.error, msg:
        usage(1, msg) 
Example 33
Project: pyblish-win   Author: pyblish   File: ndiff.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(args):
    import getopt
    try:
        opts, args = getopt.getopt(args, "qr:")
    except getopt.error, detail:
        return fail(str(detail)) 
Example 34
Project: pyblish-win   Author: pyblish   File: untabify.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    tabsize = 8
    try:
        opts, args = getopt.getopt(sys.argv[1:], "t:")
        if not args:
            raise getopt.error, "At least one file argument required"
    except getopt.error, msg:
        print msg
        print "usage:", sys.argv[0], "[-t tabwidth] file ..."
        return 
Example 35
Project: pyblish-win   Author: pyblish   File: finddiv.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "lh")
    except getopt.error, msg:
        usage(msg)
        return 2 
Example 36
Project: pyblish-win   Author: pyblish   File: cvsfiles.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "n:")
    except getopt.error, msg:
        print msg
        print __doc__,
        return 1 
Example 37
Project: pyblish-win   Author: pyblish   File: cleanfuture.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    import getopt
    global verbose, recurse, dryrun
    try:
        opts, args = getopt.getopt(sys.argv[1:], "drv")
    except getopt.error, msg:
        errprint(msg)
        return 
Example 38
Project: pyblish-win   Author: pyblish   File: checkappend.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    args = sys.argv[1:]
    global verbose
    try:
        opts, args = getopt.getopt(sys.argv[1:], "v")
    except getopt.error, msg:
        errprint(str(msg) + "\n\n" + __doc__)
        return 
Example 39
Project: pyblish-win   Author: pyblish   File: fixcid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'crs:')
    except getopt.error, msg:
        err('Options error: ' + str(msg) + '\n')
        usage()
        sys.exit(2) 
Example 40
Project: pyblish-win   Author: pyblish   File: findlinksto.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], '')
        if len(args) < 2:
            raise getopt.GetoptError('not enough arguments', None)
    except getopt.GetoptError, msg:
        sys.stdout = sys.stderr
        print msg
        print 'usage: findlinksto pattern directory ...'
        sys.exit(2) 
Example 41
Project: pyblish-win   Author: pyblish   File: checkversions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    global VERBOSE
    try:
        options, arguments = getopt.getopt(sys.argv[1:], 'v:')
    except getopt.error:
        print USAGE
        sys.exit(1)
    for o, a in options:
        if o == '-v':
            VERBOSE = int(a)
    if not arguments:
        arguments = [sys.prefix]
    for dir in arguments:
        walk1tree(dir) 
Example 42
Project: pyblish-win   Author: pyblish   File: msgfmt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
                                   ['help', 'version', 'output-file='])
    except getopt.error, msg:
        usage(1, msg) 
Example 43
Project: pyblish-win   Author: pyblish   File: modulefinder.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test():
    # Parse command line
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:")
    except getopt.error, msg:
        print msg
        return

    # Process options 
Example 44
Project: pyblish-win   Author: pyblish   File: fileinput.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _test():
    import getopt
    inplace = 0
    backup = 0
    opts, args = getopt.getopt(sys.argv[1:], "ib:")
    for o, a in opts:
        if o == '-i': inplace = 1
        if o == '-b': backup = a
    for line in input(args, inplace=inplace, backup=backup):
        if line[-1:] == '\n': line = line[:-1]
        if line[-1:] == '\r': line = line[:-1]
        print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
                                   isfirstline() and "*" or "", line)
    print "%d: %s[%d]" % (lineno(), filename(), filelineno()) 
Example 45
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(*packages):
    try:
        opts, args = getopt.getopt(sys.argv[1:], "rqvu:x:")
    except getopt.error:
        return usage()

    verbosity = 1
    search_leaks = False
    exclude = []
    for flag, value in opts:
        if flag == "-q":
            verbosity -= 1
        elif flag == "-v":
            verbosity += 1
        elif flag == "-r":
            try:
                sys.gettotalrefcount
            except AttributeError:
                print >> sys.stderr, "-r flag requires Python debug build"
                return -1
            search_leaks = True
        elif flag == "-u":
            use_resources.extend(value.split(","))
        elif flag == "-x":
            exclude.extend(value.split(","))

    mask = "test_*.py"
    if args:
        mask = args[0]

    for package in packages:
        run_tests(package, mask, verbosity, search_leaks, exclude) 
Example 46
Project: pyblish-win   Author: pyblish   File: fancy_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getopt (self, args=None, object=None):
        """Parse command-line options in args. Store as attributes on object.

        If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If
        'object' is None or not supplied, creates a new OptionDummy
        object, stores option values there, and returns a tuple (args,
        object).  If 'object' is supplied, it is modified in place and
        'getopt()' just returns 'args'; in both cases, the returned
        'args' is a modified copy of the passed-in 'args' list, which
        is left untouched.
        """
        if args is None:
            args = sys.argv[1:]
        if object is None:
            object = OptionDummy()
            created_object = 1
        else:
            created_object = 0

        self._grok_option_table()

        short_opts = string.join(self.short_opts)
        try:
            opts, args = getopt.getopt(args, short_opts, self.long_opts)
        except getopt.error, msg:
            raise DistutilsArgError, msg 
Example 47
Project: pyblish-win   Author: pyblish   File: fancy_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_option_order (self):
        """Returns the list of (option, value) tuples processed by the
        previous run of 'getopt()'.  Raises RuntimeError if
        'getopt()' hasn't been called yet.
        """
        if self.option_order is None:
            raise RuntimeError, "'getopt()' hasn't been called yet"
        else:
            return self.option_order 
Example 48
Project: pyblish-win   Author: pyblish   File: fancy_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def fancy_getopt (options, negative_opt, object, args):
    parser = FancyGetopt(options)
    parser.set_negative_aliases(negative_opt)
    return parser.getopt(args, object) 
Example 49
Project: pyblish-win   Author: pyblish   File: compileall.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    """Script main program."""
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:i:')
    except getopt.error, msg:
        print msg
        print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
              "[-x regexp] [-i list] [directory|file ...]"
        print
        print "arguments: zero or more file and directory names to compile; " \
              "if no arguments given, "
        print "           defaults to the equivalent of -l sys.path"
        print
        print "options:"
        print "-l: don't recurse into subdirectories"
        print "-f: force rebuild even if timestamps are up-to-date"
        print "-q: output only error messages"
        print "-d destdir: directory to prepend to file paths for use in " \
              "compile-time tracebacks and in"
        print "            runtime tracebacks in cases where the source " \
              "file is unavailable"
        print "-x regexp: skip files matching the regular expression regexp; " \
              "the regexp is searched for"
        print "           in the full path of each file considered for " \
              "compilation"
        print "-i file: add all the files and directories listed in file to " \
              "the list considered for"
        print '         compilation; if "-", names are read from stdin'

        sys.exit(2) 
Example 50
Project: pyblish-win   Author: pyblish   File: base64.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test():
    """Small test program"""
    import sys, getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'deut')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print """usage: %s [-d|-e|-u|-t] [file|-]
        -d, -u: decode
        -e: encode (default)
        -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
        sys.exit(2) 
Example 51
Project: pyblish-win   Author: pyblish   File: xmllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test(args = None):
    import sys, getopt
    from time import time

    if not args:
        args = sys.argv[1:]

    opts, args = getopt.getopt(args, 'st')
    klass = TestXMLParser
    do_time = 0
    for o, a in opts:
        if o == '-s':
            klass = XMLParser
        elif o == '-t':
            do_time = 1

    if args:
        file = args[0]
    else:
        file = 'test.xml'

    if file == '-':
        f = sys.stdin
    else:
        try:
            f = open(file, 'r')
        except IOError, msg:
            print file, ":", msg
            sys.exit(1) 
Example 52
Project: pyblish-win   Author: pyblish   File: quopri.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    import sys
    import getopt
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'td')
    except getopt.error, msg:
        sys.stdout = sys.stderr
        print msg
        print "usage: quopri [-t | -d] [file] ..."
        print "-t: quote tabs"
        print "-d: decode; default encode"
        sys.exit(2) 
Example 53
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    import getopt
    usage = """Usage: %s [-n | -t] url
    -n: open new window
    -t: open new tab""" % sys.argv[0]
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'ntd')
    except getopt.error, msg:
        print >>sys.stderr, msg
        print >>sys.stderr, usage
        sys.exit(1) 
Example 54
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(tests=None, testdir=None, verbose=0, quiet=False,
         exclude=False, single=False, randomize=False, fromfile=None,
         findleaks=False, use_resources=None, trace=False, coverdir='coverage',
         runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
         random_seed=None, use_mp=None, verbose3=False, forever=False,
         header=False):
    """Execute a test suite.

    This also parses command-line options and modifies its behavior
    accordingly.

    tests -- a list of strings containing test names (optional)
    testdir -- the directory in which to look for tests (optional)

    Users other than the Python test suite will certainly want to
    specify testdir; if it's omitted, the directory containing the
    Python test suite is searched for.

    If the tests argument is omitted, the tests listed on the
    command-line will be used.  If that's empty, too, then all *.py
    files beginning with test_ will be used.

    The other default arguments (verbose, quiet, exclude,
    single, randomize, findleaks, use_resources, trace, coverdir,
    print_slow, and random_seed) allow programmers calling main()
    directly to set the values that would normally be set by flags
    on the command line.
    """

    test_support.record_original_stdout(sys.stdout)
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:j:',
            ['help', 'verbose', 'verbose2', 'verbose3', 'quiet',
             'exclude', 'single', 'slow', 'randomize', 'fromfile=', 'findleaks',
             'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir',
             'runleaks', 'huntrleaks=', 'memlimit=', 'randseed=',
             'multiprocess=', 'slaveargs=', 'forever', 'header'])
    except getopt.error, msg:
        usage(2, msg)

    # Defaults 
Example 55
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def assertError(self, *args, **kwargs):
        self.assertRaises(getopt.GetoptError, *args, **kwargs) 
Example 56
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_short_has_arg(self):
        self.assertTrue(getopt.short_has_arg('a', 'a:'))
        self.assertFalse(getopt.short_has_arg('a', 'a'))
        self.assertError(getopt.short_has_arg, 'a', 'b') 
Example 57
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_libref_examples(self):
        s = """
        Examples from the Library Reference:  Doc/lib/libgetopt.tex

        An example using only Unix style options:


        >>> import getopt
        >>> args = '-a -b -cfoo -d bar a1 a2'.split()
        >>> args
        ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'abc:d:')
        >>> optlist
        [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
        >>> args
        ['a1', 'a2']

        Using long option names is equally easy:


        >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
        >>> args = s.split()
        >>> args
        ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'x', [
        ...     'condition=', 'output-file=', 'testing'])
        >>> optlist
        [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
        >>> args
        ['a1', 'a2']
        """

        import types
        m = types.ModuleType("libreftest", s)
        run_doctest(m, verbose) 
Example 58
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_issue4629(self):
        longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
        self.assertEqual(longopts, [('--help', '')])
        longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
        self.assertEqual(longopts, [('--help', 'x')])
        self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) 
Example 59
Project: NSAEQGRPFortinetVerify   Author: fnatalucci   File: check_fortinet_vuln.py    MIT License 5 votes vote down vote up
def main(argv):
    try:
        opts, args = getopt.getopt(argv, "hi:d", ["ip="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    if not opts:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print '### HELP? ma LOL ###'
            sys.exit()
        elif opt == "-i":
            ipToCheck = arg
         

    print '## Checking IP:',arg

    print '## Verify EGBL...'
    verifyConfig()
     
    print '## Check vulnerability...'
    verifyVuln(ipToCheck) 
Example 60
Project: openhatch   Author: campbe13   File: reindent.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def main():
    import getopt
    global verbose, recurse, dryrun, no_backup

    try:
        opts, args = getopt.getopt(sys.argv[1:], "drvhB",
                                   ["dryrun", "recurse", "verbose", "help",
                                    "no-backup"])
    except getopt.error, msg:
        usage(msg)
        return 
Example 61
Project: pr-automerger-bot   Author: Repo3DS   File: brewman.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(argv):
	inputfile = ''
	dirname = ''
	try:
		opts, args = getopt.getopt(argv,"hi:d:",["help","file=","dir="])
	except getopt.GetoptError:
		print_help()
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			print_help()
			sys.exit()
		elif opt in ("-i", "--file"):
			inputfile = arg
		elif opt in ("-d", "--dir"):
			dirname = arg

	if inputfile and dirname:
		try:
			with open(inputfile) as f:
				config = yaml.load(f)
				app = BrewConfig(config, dirname)
				errorlist = app.validate()
				if errorlist:
					for error in errorlist:
						print(error)
				else:
					print("Validated successfully")
		except yaml.YAMLError as e:
			print("Error in configuration file:", e)
	else:
		print_help() 
Example 62
Project: dvrip   Author: alexshpilkin   File: discover.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(args: List[str]) -> None:
	try:
		opts, args = getopt(args, 'i:t:')
	except GetoptError:
		usage()
	if args:
		usage()

	interface = ''
	timeout   = 1.0
	for opt, arg in opts:
		if opt == '-i':
			try:
				interface = gethostbyname(arg)
			except OSError as e:
				osexit(e, EX_NOHOST)
		if opt == '-t':
			try:
				timeout = float(arg)
			except ValueError:
				usage()

	for result in DVRIPClient.discover(interface, timeout):
		print('{} {} {} {}/{} via {} port {} channels {}'
		      .format(result.serial, result.mac, result.name,
		              result.host, result.mask, result.router,
		              result.tcpport, result.channels)) 
Example 63
Project: dvrip   Author: alexshpilkin   File: log.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(host: str,
        serv: int,
        username: str,
        password: str,
        args: List[str]
       ) -> None:
	try:
		opts, args = getopt(args, 's:e:')
	except GetoptError:
		usage()
	if args:
		usage()

	start = EPOCH
	end = datetime.now()
	for opt, arg in opts:
		if opt == '-s':
			from dateparser import parse  # type: ignore
			start = parse(arg)
			if start is None:
				usage()
		if opt == '-e':
			from dateparser import parse  # type: ignore
			end = parse(arg)
			if end is None:
				usage()

	conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
	conn.connect((host, serv), username, password)
	try:
		for entry in conn.log(start=start, end=end):
			print('{:>8} {} {:>12} {}'
			      .format(entry.number,
			              entry.time.isoformat(),
			              entry.type.name.lower(),
			              entry.data))
	finally:
		conn.logout() 
Example 64
Project: resticprofile   Author: creativeprojects   File: context.py    GNU General Public License v3.0 5 votes vote down vote up
def load_context_from_command_line(self, argv: list):
        try:
            short_options = self._get_short_options()
            long_options = self._get_long_options()
            self.opts, self.args = getopt(argv[1:], short_options, long_options)

        except GetoptError as err:
            console = Console()
            console.error("Error in the command arguments: " + err.msg)
            console.usage(argv[0])
            exit(2)

        for option, argument in self.opts:
            if option in self._get_possible_options_for('help'):
                Console().usage(argv[0])
                exit()

            elif option in self._get_possible_options_for('quiet'):
                self.quiet = True

            elif option in self._get_possible_options_for('verbose'):
                self.verbose = True

            elif option in self._get_possible_options_for('config'):
                self.configuration_file = argument

            elif option in self._get_possible_options_for('name'):
                self.profile_name = argument

            elif option in self._get_possible_options_for('no-ansi'):
                self.ansi = False

            else:
                assert False, "unhandled option" 
Example 65
Project: firmanal   Author: kyechou   File: makeNetwork.py    MIT License 5 votes vote down vote up
def main():
    infile = None
    makeQemuCmd = False
    iid = None
    outfile = None
    arch = None
    endianness = None
    (opts, argv) = getopt.getopt(sys.argv[1:], 'f:i:S:a:oqd')
    for (k, v) in opts:
        if k == '-f':
            infile = v
        if k == '-d':
            global debug
            debug += 1
        if k == '-q':
            makeQemuCmd = True
        if k == '-i':
            iid = int(v)
        if k == '-S':
            VMDIR = v
        if k == '-o':
            outfile = True
        if k == '-a':
            (arch, endianness) = archEnd(v)

    if not arch or not endianness:
        raise Exception("Either arch or endianness not found try mipsel/mipseb/armel/armeb")

    if not infile and iid:
        infile = "%s/%i/qemu.initial.serial.log" % (VMDIR, iid)
    if outfile and iid:
        outfile = """%s/%i/run.sh""" % (VMDIR, iid)
    if debug:
        print("processing %i" % iid)
    if infile:
        process(infile, iid, arch, endianness, makeQemuCmd, outfile) 
Example 66
Project: Adversarial_Video_Generation   Author: dyelax   File: process_data.py    MIT License 5 votes vote down vote up
def main():
    ##
    # Handle command line input
    ##

    num_clips = 5000000

    try:
        opts, _ = getopt.getopt(sys.argv[1:], 'n:t:c:oH',
                                ['num_clips=', 'train_dir=', 'clips_dir=', 'overwrite', 'help'])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-n', '--num_clips'):
            num_clips = int(arg)
        if opt in ('-t', '--train_dir'):
            c.TRAIN_DIR = c.get_dir(arg)
        if opt in ('-c', '--clips_dir'):
            c.TRAIN_DIR_CLIPS = c.get_dir(arg)
        if opt in ('-o', '--overwrite'):
            c.clear_dir(c.TRAIN_DIR_CLIPS)
        if opt in ('-H', '--help'):
            usage()
            sys.exit(2)

    # set train frame dimensions
    assert os.path.exists(c.TRAIN_DIR)
    c.FULL_HEIGHT, c.FULL_WIDTH = c.get_train_frame_dims()

    ##
    # Process data for training
    ##

    process_training_data(num_clips) 
Example 67
Project: pyWeatherGrab   Author: shazzner   File: pyWeatherGrab.py    GNU General Public License v2.0 5 votes vote down vote up
def parse_options():
    try:
        long_options = ['serial-port', 'baud', 'help', 'settings']
        opts, args = getopt.getopt(sys.argv[1:], "s:hb:i:", long_options)
    except getopt.GetoptError, e:
        print help()
        sys.exit(3)

    # Default options 
Example 68
Project: spy-ggp   Author: syllag   File: server.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def treat_opts(argv):
    try:
        opts, args = getopt.getopt(argv, 'hp:i:l::', ['help', 'lib_path=','lib_name=', 'port=', 'interface=', 'loglevel=', 'gdl_version='])

    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(-1)

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif opt == '--lib_path':
            CONFIG['DLL_PATH']  = os.path.normpath(arg)
            print(CONFIG)
        elif opt == '--lib_name':
            CONFIG['DLL_NAME']  = arg
        elif opt == '--gdl_version':
            CONFIG['GDL_VERSION']  = arg
        elif opt in ('--port', '-p'):
            CONFIG['PORT']      = int(arg)
        elif opt in ('--interface', '-i'):
            CONFIG['IP']        = arg
        elif opt in ('loglevel=', '-l'):
            CONFIG['LOG_LEVEL'] = int(arg) 
Example 69
Project: steam_workshop_downloader   Author: Geam   File: workshop.py    MIT License 5 votes vote down vote up
def init(argv):
    """Read the args and return all variable
    Will return:
        - the number of error encounter
        - the absolute path of the output directory
        - an array of collection id given as args (in fact everything that is
            not a recognised arg
        - the absolute path of the save file
    Return int(error), string(output_dir), array(collections_id),
        string(save_file)
    """
    error = 0
    output_dir = os.getcwd()
    collections_id_list = []
    save_file = os.path.join(output_dir, "addons.lst")
    if len(argv) == 1 and not os.path.isfile(save_file):
        print("No save file found")
        usage(argv[0], 0)
    try:
        opts, args = getopt.getopt(argv[1:],"ho:")
    except getopt.GetoptError:
        usge(argv[0], 2)
    else:
        for opt, arg in opts:
            if opt == 'h':
                usge(argv[0], 0)
            elif opt == '-o':
                output_dir = os.path.abspath(arg)
                save_file = os.path.join(output_dir, "addons.lst")
        if not os.path.exists(output_dir):
            print(output_dir + ": path doesn't exist\nEnd of program")
            error += 1
        collections_id_list = argv[len(opts) * 2 + 1:]
    return error, output_dir, collections_id_list, save_file 
Example 70
Project: mininet_utils   Author: samueljero   File: traffic_source.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
	global client,port, fancy_names
	dns = []
	zero = 0
	tmdilation = 1
	try:                                
		opts, args = getopt.getopt(sys.argv[1:], "hc:p:d:z:f", ["help","client=", "port=","dns=", "zero=", "dilation="])
	except getopt.GetoptError:
		usage()
		sys.exit(2)
	for opt,arg in opts:
		if opt in ("-c", "--client"):
			client=arg
		elif opt in ("-p", "--port"):
			port=int(arg)
		elif opt in ("-d", "--dns"):
			dfile=arg
			dns=parse_dns(dfile)
		elif opt in ("-z", "--zero"):
			zero=float(arg)
		elif opt in ("-f", "--dilation"):
			tmdilation=float(arg)
		elif opt in ("-h", "--help"):
			usage()
			sys.exit()
		else:
			print "Unknown Option"
			sys.exit()
	infiles=args
	if len(infiles)==0:
		print "Error, no matrices"
		sys.exit()
	flows, rtime=parse_mats(infiles, client,dns,tmdilation)
	flows=sort_flows(flows)
	do_test(flows,port, rtime, client,dns, zero) 
Example 71
Project: Repobot   Author: Desgard   File: cmdline.py    MIT License 5 votes vote down vote up
def main(args=sys.argv):
    """
    Main command line entry point.
    """
    usage = USAGE % ((args[0],) * 6)

    try:
        popts, args = getopt.getopt(args[1:], "l:f:F:o:O:P:LS:a:N:vhVHgsx")
    except getopt.GetoptError:
        print(usage, file=sys.stderr)
        return 2

    try:
        return main_inner(popts, args, usage)
    except Exception:
        if '-v' in dict(popts):
            print(file=sys.stderr)
            print('*' * 65, file=sys.stderr)
            print('An unhandled exception occurred while highlighting.',
                  file=sys.stderr)
            print('Please report the whole traceback to the issue tracker at',
                  file=sys.stderr)
            print('<https://bitbucket.org/birkenfeld/pygments-main/issues>.',
                  file=sys.stderr)
            print('*' * 65, file=sys.stderr)
            print(file=sys.stderr)
            raise
        import traceback
        info = traceback.format_exception(*sys.exc_info())
        msg = info[-1].strip()
        if len(info) >= 3:
            # extract relevant file and position info
            msg += '\n   (f%s)' % info[-2].split('\n')[0].strip()[1:]
        print(file=sys.stderr)
        print('*** Error while highlighting:', file=sys.stderr)
        print(msg, file=sys.stderr)
        print('*** If this is a bug you want to report, please rerun with -v.',
              file=sys.stderr)
        return 1 
Example 72
Project: bitcointalk-sentiment   Author: DolphinBlockchainIntelligence   File: bitcointalk_batch_classifier.py    MIT License 5 votes vote down vote up
def main(argv):
    input_folder = ''
    model_file = ''
    output_folder = ''
    announce_json = ''
    sentiment_json = ''
    output_posts = ''

    try:
        opts, args = getopt.getopt(argv, "hi:m:f:a:s:n:")
    except getopt.GetoptError:
        print('bitcointalk_batch_classifier.py -i <input folder> -m <model> -f <output folder> -a <announce JSON> -s <sentiment JSON> -n <number of output posts [number|fraction|all]>')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print('bitcointalk_batch_classifier.py -i <input folder> -m <model> -f <output folder> -a <announce JSON> -s <sentiment JSON> -n <number of output posts [number|fraction|all]>')
        elif opt == '-i':
            input_folder = arg
        elif opt == '-m':
            model_file = arg
        elif opt == '-f':
            output_folder = arg
        elif opt == '-a':
            announce_json = arg
        elif opt == '-s':
            sentiment_json = arg
        elif opt == '-n':
            output_posts = arg

    batch_classify(input_folder, model_file, output_folder, announce_json, sentiment_json, output_posts) 
Example 73
Project: pyblish-win   Author: pyblish   File: objgraph.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def main():
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'cdu')
    except getopt.error:
        sys.stdout = sys.stderr
        print 'Usage:', os.path.basename(sys.argv[0]),
        print           '[-cdu] [file] ...'
        print '-c: print callers per objectfile'
        print '-d: print callees per objectfile'
        print '-u: print usage of undefined symbols'
        print 'If none of -cdu is specified, all are assumed.'
        print 'Use "nm -o" to generate the input (on IRIX: "nm -Bo"),'
        print 'e.g.: nm -o /lib/libc.a | objgraph'
        return 1
    optu = optc = optd = 0
    for opt, void in optlist:
        if opt == '-u':
            optu = 1
        elif opt == '-c':
            optc = 1
        elif opt == '-d':
            optd = 1
    if optu == optc == optd == 0:
        optu = optc = optd = 1
    if not args:
        args = ['-']
    for filename in args:
        if filename == '-':
            readinput(sys.stdin)
        else:
            readinput(open(filename, 'r'))
    #
    warndups()
    #
    more = (optu + optc + optd > 1)
    if optd:
        if more:
            print '---------------All callees------------------'
        printcallee()
    if optu:
        if more:
            print '---------------Undefined callees------------'
        printundef()
    if optc:
        if more:
            print '---------------All Callers------------------'
        printcaller()
    return 0

# Call the main program.
# Use its return value as exit status.
# Catch interrupts to avoid stack trace.
# 
Example 74
Project: pyblish-win   Author: pyblish   File: fancy_getopt.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def __init__ (self, option_table=None):

        # The option table is (currently) a list of tuples.  The
        # tuples may have 3 or four values:
        #   (long_option, short_option, help_string [, repeatable])
        # if an option takes an argument, its long_option should have '='
        # appended; short_option should just be a single character, no ':'
        # in any case.  If a long_option doesn't have a corresponding
        # short_option, short_option should be None.  All option tuples
        # must have long options.
        self.option_table = option_table

        # 'option_index' maps long option names to entries in the option
        # table (ie. those 3-tuples).
        self.option_index = {}
        if self.option_table:
            self._build_index()

        # 'alias' records (duh) alias options; {'foo': 'bar'} means
        # --foo is an alias for --bar
        self.alias = {}

        # 'negative_alias' keeps track of options that are the boolean
        # opposite of some other option
        self.negative_alias = {}

        # These keep track of the information in the option table.  We
        # don't actually populate these structures until we're ready to
        # parse the command-line, since the 'option_table' passed in here
        # isn't necessarily the final word.
        self.short_opts = []
        self.long_opts = []
        self.short2long = {}
        self.attr_name = {}
        self.takes_arg = {}

        # And 'option_order' is filled up in 'getopt()'; it records the
        # original order of options (and their values) on the command-line,
        # but expands short options, converts aliases, etc.
        self.option_order = []

    # __init__ () 
Example 75
Project: programsynthesishunting   Author: flexgp   File: stats_parser.py    GNU General Public License v3.0 4 votes vote down vote up
def parse_opts(command_line_args):
    """
    Parses command line arguments and returns usable variables which are used
    as inputs for other functions in this file.
    
    :param command_line_args: flags passed in from the command line at
    execution
    :return: experiment_name: the name of the containing folder of results,
             stats: a list of strings. Each string is a valid key from the
                    stats.stats.stats dictionary.
             graph: an optional boolean flag for graphing specified stats.
    """
    
    try:
        opts, args = getopt.getopt(command_line_args[1:], "",
                                   ["help", "experiment_name="])
    except getopt.GetoptError as err:
        s = "scripts.parse_stats.parse_opts\n" \
            "Error: in order to parse stats you need to specify the location" \
            " of the target stats files.\n" \
            "       Run python stats_parser.py --help for more info."
        print(str(err))
        raise Exception(s)

    if not opts:
        s = "scripts.parse_stats.parse_opts\n" \
            "Error: in order to parse stats you need to specify the location" \
            " of the target stats files.\n" \
            "       Run python stats_parser.py --help for more info."
        raise Exception(s)

    experiment_name = None
    
    # iterate over all arguments in the option parser.
    for opt, arg in opts:
        if opt == "--help":
            # Print help message.
            help_message()
            exit()
        
        elif opt == "--experiment_name":
            # Set experiment name (i.e. containing folder for multiple runs).
            experiment_name = arg
                    
    return experiment_name 
Example 76
Project: idmp_vaulx   Author: bobjohnbobjohn   File: idmp_extraction.py    The Unlicense 4 votes vote down vote up
def parse_options():
    """Deal with command line parameters"""
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ulsm:d:h:p:o:")
    except getopt.GetoptError as err:
        sys.stderr.write(err)
        sys.stderr.write("\nUse {program} -u to have usage information.\n".format(program=PROGRAM))
        sys.exit(EXIT_FAILURE)

    month = None
    day = None
    hour = None
    params = None
    output = None
    global PRINT_HEADER

    for o, a in opts:
        if o == "-u":
            print_usage()
            sys.exit(EXIT_SUCCESS)
        elif o == "-l":
            print_params()
            sys.exit(EXIT_SUCCESS)
        elif o == "-s":
            PRINT_HEADER = False
        elif o == "-m":
            month = check_values(MONTH, a.split(','))
        elif o == "-d":
            day = check_values(DAY, a.split(','))
        elif o == "-h":
            hour = check_values(HOUR, a.split(','))
        elif o == "-p":
            params = check_params(a.split(','))
        elif o == "-o":
            output = a
        else:
            assert False, "Unhandled option"

    if len(args) != 1:
        sys.stderr.write(
            "Missing file name.\nUse {program} -u to have usage information.\n"
            .format(program=PROGRAM))
        sys.exit(EXIT_FAILURE)

    if not params:
        sys.stderr.write("No parameter selected, use -p option.\n")
        sys.exit(EXIT_FAILURE)


    if len(opts) < 1:
        sys.stderr.write(
            "You must apply a filter.\nUse {program} -u to have usage information.\n"
            .format(program=PROGRAM))
        sys.exit(EXIT_FAILURE)
    else:
        input = args[0]

    return month, day, hour, params, input, output 
Example 77
Project: zabbix   Author: xiaomatech   File: hdfs-parse.py    MIT License 4 votes vote down vote up
def main(argv):
    inputfile, context, metric = "", "", ""
    help_string = "Usage:\n./%s -i <input_file>" % (argv[0])
    try:
        opts, args = getopt.getopt(argv[1:], "hi:c:m:",
                                   ["input", "context", "metric"])
    except getopt.GetoptError:
        print help_string
        sys.exit(2)

    for opt, arg in opts:
        if opt == "-h":
            print help_string
            sys.exit()
        elif opt in ("-i", "--input"):
            inputfile = arg
        elif opt in ("-c", "--context"):
            context = arg
        elif opt in ("-m", "--metric"):
            metric = arg

    try:
        with open(inputfile, "r") as f:
            data = json.loads(f.read())
            if context not in ['dfs', 'metricssystem', 'ugi', 'jvm', 'rpc']:
                print "Unknown context '%s'" % context
                sys.exit(1)

            data = data[context]
            if metric not in data.keys():
                print "Unknown metric '%s'" % metric
                sys.exit(1)

            values = data[metric]
            if type(values) is list:
                # Sum value
                values = [float(x) if "." in x else int(x) for x in values]
                values = sum(values) / len(values)
            print values
    except IOError:
        print "Error, cant read or write to file '%s'" % outputfile
        sys.exit(2) 
Example 78
Project: adversarial_da_icvgip18   Author: abhinavagarwalla   File: source_to_target_model_copy.py    MIT License 4 votes vote down vote up
def main(argv):
    checkpoint_dir = None
    checkpoint_save_dir = None
    replace_from = None
    replace_to = None
    add_prefix = None
    dry_run = False

    try:
        opts, args = getopt.getopt(argv, 'h', ['help=', 'checkpoint_dir=', 'checkpoint_save_dir=', 'replace_from=',
                                               'replace_to=', 'add_prefix=', 'dry_run'])
    except getopt.GetoptError:
        print(usage_str)
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print(usage_str)
            sys.exit()
        elif opt == '--checkpoint_dir':
            checkpoint_dir = arg
        elif opt == '--checkpoint_save_dir':
            checkpoint_save_dir = arg
        elif opt == '--replace_from':
            replace_from = arg
        elif opt == '--replace_to':
            replace_to = arg
        elif opt == '--add_prefix':
            add_prefix = arg
        elif opt == '--dry_run':
            dry_run = True

    if not checkpoint_dir:
        print('Please specify a checkpoint_dir. Usage:')
        print(usage_str)
        sys.exit(2)

    if not checkpoint_save_dir:
        print('Please specify a checkpoint_save_dir. Usage:')
        print(usage_str)
        sys.exit(2)

    rename(checkpoint_dir, checkpoint_save_dir, replace_from, replace_to, add_prefix, dry_run) 
Example 79
Project: MyDotfiles   Author: Sup3r-Us3r   File: mem.py    GNU General Public License v3.0 4 votes vote down vote up
def parse_options():
    try:
        long_options = [
            'split-args',
            'help',
            'total',
            'discriminate-by-pid',
            'swap'
        ]
        opts, args = getopt.getopt(sys.argv[1:], "shtdSp:w:", long_options)
    except getopt.GetoptError:
        sys.stderr.write(help())
        sys.exit(3)

    if len(args):
        sys.stderr.write("Extraneous arguments: %s\n" % args)
        sys.exit(3)

    # ps_mem.py options
    split_args = False
    pids_to_show = None
    discriminate_by_pid = False
    show_swap = False
    watch = None
    only_total = False

    for o, a in opts:
        if o in ('-s', '--split-args'):
            split_args = True
        if o in ('-t', '--total'):
            only_total = True
        if o in ('-d', '--discriminate-by-pid'):
            discriminate_by_pid = True
        if o in ('-S', '--swap'):
            show_swap = True
        if o in ('-h', '--help'):
            sys.stdout.write(help())
            sys.exit(0)
        if o in ('-p',):
            try:
                pids_to_show = [int(x) for x in a.split(',')]
            except:
                sys.stderr.write(help())
                sys.exit(3)
        if o in ('-w',):
            try:
                watch = int(a)
            except:
                sys.stderr.write(help())
                sys.exit(3)

    return (
        split_args,
        pids_to_show,
        watch,
        only_total,
        discriminate_by_pid,
        show_swap
    ) 
Example 80
Project: naftawayh   Author: linuxscout   File: test_wordtag_quran.py    GNU General Public License v3.0 4 votes vote down vote up
def grabargs():
#  "Grab command-line arguments"
    all = False;
    segmentation=False;
    dictionarybased=False;
    templatesearch=False;
    rootextraction=False;
    vocalized=False;
    convert=False;
    fname = ''

    if not sys.argv[1:]:
        usage()
        sys.exit(0)
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hVdrtsv:f:",
                               ["help", "version","dict", "root", "template","all",
                                "seg", "vocalized", "file="],)
    except getopt.GetoptError:
        usage()
        sys.exit(0)
    for o, val in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        if o in ("-V", "--version"):
            print scriptversion
            sys.exit(0)
        if o in ("-s", "--seg"):
            segmentation = True
        if o in ("-f", "--file"):
            fname = val
        if o in ("-d", "--dict"):
            dictionarybased = True
        if o in ("-r", "--root"):
            rootextraction=True;
        if o in ("-t", "--template"):

            templatesearch =True;
        if o in ("-v", "--vocalized"):
            vocalized =True;
        if o in ("-c", "--convert"):
            convert =True;
    return (fname,segmentation,dictionarybased,templatesearch,rootextraction,vocalized,convert)