Python getopt.getopt() Examples

The following are code examples for showing how to use getopt.getopt(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: python-   Author: secondtonone1   File: base64.py    (license) View Source Project 7 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 2
Project: core-framework   Author: RedhawkSDR   File: rhunittest.py    (license) View Source Project 7 votes vote down vote up
def parseArgs(self, argv):
        try:
            options, args = getopt.getopt(argv[1:], 'hHvqi:',
                                          ['help','verbose','quiet','impl='])
            for opt, value in options:
                if opt in ('-h','-H','--help'):
                    self.usageExit()
                if opt in ('-q','--quiet'):
                    self.verbosity = 0
                if opt in ('-v','--verbose'):
                    self.verbosity = 2
                if opt in ('-i','--impl'):
                    self.testLoader.impl = value
            if len(args) == 0 and self.defaultTest is None:
                self.test = self.testLoader.loadTestsFromModule(self.module)
                return
            if len(args) > 0:
                self.testNames = args
            else:
                self.testNames = (self.defaultTest,)
            self.createTests()
        except getopt.error, msg:
            self.usageExit(msg) 
Example 3
Project: kinect-2-libras   Author: inessadl   File: tabnanny.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def main():
    global verbose, filename_only
    try:
        opts, args = getopt.getopt(sys.argv[1:], "qv")
    except getopt.error, msg:
        errprint(msg)
        return
    for o, a in opts:
        if o == '-q':
            filename_only = filename_only + 1
        if o == '-v':
            verbose = verbose + 1
    if not args:
        errprint("Usage:", sys.argv[0], "[-v] file_or_directory ...")
        return
    for arg in args:
        check(arg) 
Example 4
Project: encore.ai   Author: dyelax   File: save_samples.py    (MIT License) View Source Project 7 votes vote down vote up
def main():
    artist = 'kanye_west'
    model_path = '../save/models/kanye_west/kanye_west.ckpt-30000'
    num_save = 1000

    try:
        opts, _ = getopt.getopt(sys.argv[1:], 'l:a:N:', ['load_path=', 'artist_name=', 'num_save='])
    except getopt.GetoptError:
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-l', '--load_path'):
            model_path = arg
        if opt in ('-a', '--artist_name'):
            artist = arg
        if opt in ('-n', '--num_save'):
            num_save = int(arg)

    save(artist, model_path, num_save) 
Example 5
Project: code   Author: ActiveState   File: recipe-224043.py    (MIT License) View Source Project 7 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
    for o, a in opts:
        if o == "-q":
            verbose = 0
        if o == "-v":
            verbose = verbose + 1
    c = Sucker()
    c.setflags(verbose=verbose)
    c.urlopener.addheaders = [
            ('User-agent', 'websucker/%s' % __version__),
        ]
    for arg in args:
        print "Adding root", arg
        c.addroot(arg)
    print "Run..."
    c.run() 
Example 6
Project: hostapd-mana   Author: adde88   File: tabnanny.py    (license) View Source Project 7 votes vote down vote up
def main():
    global verbose, filename_only
    try:
        opts, args = getopt.getopt(sys.argv[1:], "qv")
    except getopt.error, msg:
        errprint(msg)
        return
    for o, a in opts:
        if o == '-q':
            filename_only = filename_only + 1
        if o == '-v':
            verbose = verbose + 1
    if not args:
        errprint("Usage:", sys.argv[0], "[-v] file_or_directory ...")
        return
    for arg in args:
        check(arg) 
Example 7
Project: core-framework   Author: RedhawkSDR   File: qtbrowse.py    (license) View Source Project 6 votes vote down vote up
def main():
    # Set up a console logger.
    console = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(name)-12s:%(levelname)-8s: %(message)s")
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    logging.getLogger().setLevel(logging.INFO)

    kw = {}
    longopts = ['domainname=', 'verbose']
    opts, args = getopt.getopt(sys.argv[1:], 'v', longopts)
    for opt, val in opts:
        if opt == '--domainname':
            kw['domainName'] = val
        if opt in ['-v', '--verbose']:
            kw['verbose'] = True

    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = BrowseWindow(**kw)
    w.show()
    a.exec_() 
Example 8
Project: kinect-2-libras   Author: inessadl   File: webbrowser.py    (Apache License 2.0) View Source Project 6 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)
    new_win = 0
    for o, a in opts:
        if o == '-n': new_win = 1
        elif o == '-t': new_win = 2
    if len(args) != 1:
        print >>sys.stderr, usage
        sys.exit(1)

    url = args[0]
    open(url, new_win)

    print "\a" 
Example 9
Project: kinect-2-libras   Author: inessadl   File: base64.py    (Apache License 2.0) View Source Project 6 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)
    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': test1(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout)
    else:
        func(sys.stdin, sys.stdout) 
Example 10
Project: code   Author: ActiveState   File: recipe-82748.py    (MIT License) View Source Project 6 votes vote down vote up
def Args(self, args=[]):
		# process command-line options
		try:
			opts, args = getopt.getopt(args, 'hcl:', ['help', 'clear', 'lines='])
		except getopt.error, msg:
			raise 'MyArgError'

		if len(args) > 1:
			raise 'MyArgError'
		self.file = args[0]
		
		for o, a in opts:
			if o in ('-h', '--help'):
				raise 'MyUsage'
			if o in ('-c', '--clear'):
				self.SetClear()
			if o in ('-l', '--lines'):
				self.lines_per_page	= int(a) 
Example 11
Project: casebox-vagrant   Author: KETSE   File: var.py    (GNU Affero General Public License v3.0) View Source Project 6 votes vote down vote up
def main(argv):
    _file = ''
    _var = ''
    try:
        opts, args = getopt.getopt(argv, "f:v", ["file=", "var="])
    except getopt.GetoptError:
        print 'var.py -f <file> -v <variable>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'var.py -f <file>  -v <variable>'
            sys.exit()
        elif opt in ("-f", "--file"):
            _file = arg
        elif opt in ("-v", "--var"):
            _var = '{' + arg + '}'
    f = open(_file)
    data = yaml.load(f)
    print _var.format(data)

    f.close() 
Example 12
Project: supremm   Author: ubccr   File: supremmconf.py    (GNU Lesser General Public License v3.0) View Source Project 6 votes vote down vote up
def getoptions():
    """ process comandline options """

    retdata = {"section": None, "item": None}

    opts, _ = getopt(sys.argv[1:], "s:i:h", ["section=", "item="])

    for opt in opts:
        if opt[0] in ("-s", "--section"):
            retdata['section'] = opt[1].encode("utf-8")
        if opt[0] in ("-i", "--item"):
            retdata['item'] = opt[1]
        if opt[0] in ("-h", "--help"):
            usage()
            sys.exit(0)

    if 'section' in retdata:
        return retdata

    usage()
    sys.exit(1) 
Example 13
Project: atoolbox   Author: liweitianux   File: radec2deg.py    (license) View Source Project 6 votes vote down vote up
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:",
                                   ["help", "infile="])
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(1)
        elif opt in ("-i", "--infile"):
            infile = arg
        else:
            assert False, "unhandled option"

    for line in open(infile):
        if re.match(r"^\s*#", line) or re.match(r"^\s*$", line):
            continue
        ra, dec = line.split()
        ra_deg = s_ra2deg(ra)
        dec_deg = s_dec2deg(dec)
        print("%.8f %.8f" % (ra_deg, dec_deg)) 
Example 14
Project: broadview-collector   Author: openstack   File: pt_ecmp_resolution.py    (license) View Source Project 6 votes vote down vote up
def main():

    host = None
    port = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:")
    except getopt.GetoptError as err:
        print str(err)  
        usage()
        sys.exit(2)
    for o, a in opts:
        if o == "-h":
            host = a
        elif o == "-p":
            port = a
        else:
            assert False, "unhandled option"

    x = PTECMPResolution(host, port)
    x.send() 
Example 15
Project: broadview-collector   Author: openstack   File: pt_drop_reason.py    (license) View Source Project 6 votes vote down vote up
def main():

    host = None
    port = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:")
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o == "-h":
            host = a
        elif o == "-p":
            port = a
        else:
            assert False, "unhandled option"

    x = PTDropReason(host, port)
    x.send() 
Example 16
Project: broadview-collector   Author: openstack   File: pt_lag_resolution.py    (license) View Source Project 6 votes vote down vote up
def main():

    host = None
    port = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:")
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o == "-h":
            host = a
        elif o == "-p":
            port = a
        else:
            assert False, "unhandled option"

    x = PTLAGResolution(host, port)
    x.send() 
Example 17
Project: broadview-collector   Author: openstack   File: pt_profile.py    (license) View Source Project 6 votes vote down vote up
def main():

    host = None
    port = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:")
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o == "-h":
            host = a
        elif o == "-p":
            port = a
        else:
            assert False, "unhandled option"

    x = PTProfile(host, port)
    x.send() 
Example 18
Project: broadview-collector   Author: openstack   File: pt_drop_counter_report.py    (license) View Source Project 6 votes vote down vote up
def main():

    host = None
    port = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:")
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o == "-h":
            host = a
        elif o == "-p":
            port = a
        else:
            assert False, "unhandled option"

    x = PTDropCounterReport(host, port)
    x.send() 
Example 19
Project: rtf2xml   Author: paulhtremblay   File: test.py    (license) View Source Project 6 votes vote down vote up
def __get_opts(self):
        self.__msv_jar = None
        try:
            options, arguments = getopt.getopt(sys.argv[1:], 'h', ['help', 'clean','local', 'msv-jar=' ])
        except getopt.GetoptError, error:
            sys.stderr.write(str(error))
            self.__help_message()
            sys.exit(1)
        self.__local = None
        self.__clean = None
        for opt, opt_arg in options:
            if 'msv-jar' in opt:
                self.__msv_jar = opt_arg
            if '-h' in opt or '--help' in opt:
                self.__help_message()
                sys.exit(0)
            if '--local' in opt:
                self.__local = 1
            if '--clean' in opt:
                self.__clean = 1 
Example 20
Project: gps2video   Author: teawater   File: gps2video.py    (license) View Source Project 6 votes vote down vote up
def parse_cmd(self):
        longopts = []
        for opt in self.opts:
            longopts.append(opt.option + "=")
        cmd_opts, config_file_path = getopt.getopt(sys.argv[1:], "", longopts)

        for arg, val in cmd_opts:
            for opt in self.opts:
                if "--" + opt.option == arg:
                    setattr(self, opt.attr, opt.convert(val))
                    break

        if len(config_file_path) == 0:
            self.config_file_path = "./config.ini"
        else:
            self.config_file_path = config_file_path[0] 
Example 21
Project: firecloud_developer_toolkit   Author: broadinstitute   File: run_module.py    (license) View Source Project 6 votes vote down vote up
def parse_argv_module_args(argv,module_arg_names):
    baseline_args = ['module_name','lsid','cache_path','execution_id','cwd','module_libdir','sg_prepare_template']
    arg_names = baseline_args + module_arg_names
    arg_names2 = [argname + '=' for argname in arg_names]
    (param_value_pairs,remnants)=getopt.getopt(argv,"",arg_names2)
    if len(remnants)>0:
        raise Exception ("unrecognized arguments %s"%str(remnants))
    arg_param_value_dict = {}
    missing_args = set(module_arg_names)
    for arg_pair in param_value_pairs:
        param_name = arg_pair[0][2:] #strip off '--' at start
        param_value = arg_pair[1]
        if param_name not in module_arg_names:
            continue
        missing_args.remove(param_name)
        if param_name in arg_param_value_dict:
            raise Exception('duplicated param name %s'%param_name)
        arg_param_value_dict[param_name]=param_value
    missing_args = list(missing_args)
        
    return (arg_param_value_dict,missing_args) 
Example 22
Project: office-interoperability-tools   Author: milossramek   File: gflags.py    (license) View Source Project 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 23
Project: office-interoperability-tools   Author: milossramek   File: docxtags.py    (license) View Source Project 6 votes vote down vote up
def parsecmd():
    global rankfile, genranks
    try:
        opts, Names = getopt.getopt(sys.argv[1:], "hcr:", [])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-c"):
            genranks=True
        elif o in ("-r"):
            rankfile = a
        elif o in ("-h"):
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option"
    return Names 
Example 24
Project: touch-pay-client   Author: HackPucBemobi   File: dict_diff.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    """Parse the arguments and start the main process."""
    try:
        opts, args = getopt.getopt(argv, "h", ["help"])
    except getopt.GetoptError:
        exit_with_parsing_error()
    for opt, arg in opts:
        arg = arg  # To avoid a warning from Pydev
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
    if len(args) == 2:
        params = list(get_dicts(*args))
        params.extend(get_dict_names(*args))
        compare_dicts(*params)
    else:
        exit_with_parsing_error() 
Example 25
Project: rapier   Author: apigee-labs   File: gen_openapispec.py    (license) View Source Project 6 votes vote down vote up
def main(args):
    generator = OASGenerator()
    usage = 'usage: gen_openapispec.py [-m, --yaml-merge] [-i, --include-impl] [-t --suppress-templates] filename'
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'mit', ['yaml-merge', 'include-impl', 'suppress-templates'])
    except getopt.GetoptError as err:
        sys.exit(str(err) + '\n' + usage)
    if not len(args) == 1:
        sys.exit(usage)        
    generator.set_opts(opts)
    Dumper = CustomAnchorDumper
    opts_keys = [k for k,v in opts]
    if False: #'--yaml-alias' not in opts_keys and '-m' not in opts_keys:
        Dumper.ignore_aliases = lambda self, data: True
    Dumper.add_representer(PresortedOrderedDict, yaml.representer.SafeRepresenter.represent_dict)
    Dumper.add_representer(validate_rapier.unicode_node, yaml.representer.SafeRepresenter.represent_unicode)
    Dumper.add_representer(validate_rapier.list_node, yaml.representer.SafeRepresenter.represent_list)
    openAPI_spec = generator.openAPI_spec_from_rapier(*args)
    openAPI_spec_yaml = yaml.dump(openAPI_spec, default_flow_style=False, Dumper=Dumper)
    openAPI_spec_yaml = str.replace(openAPI_spec_yaml, "'<<':", '<<:')
    print openAPI_spec_yaml 
Example 26
Project: rapier   Author: apigee-labs   File: rapier.py    (license) View Source Project 6 votes vote down vote up
def main():
    usage = 'usage: rapier [-v, --validate] [-p, --gen-python] [-j, --gen-js] [-m, --yaml-merge] [-i, --include-impl] [-t --suppress-templates] filename'
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'vpjmit', ['validate', 'gen-python', 'gen-js', 'yaml-merge', 'include-impl', 'suppress-templates'])
    except getopt.GetoptError as err:
        sys.exit(str(err) + '\n' + usage)
    if not len(args) == 1:
        sys.exit(usage)        
    opts_keys = [k for k,v in opts]

    if '-v' in opts_keys or '--validate' in opts_keys:
        validate_main(args[0])
    elif '-p' in opts_keys or '--gen-python' in opts_keys:
        gen_py_main(args[0])
    elif '-j' in opts_keys or '--gen-js' in opts_keys:
        gen_py_main(args[0])
    else:
        gen_oas_main(sys.argv) 
Example 27
Project: semantic-segmentation   Author: albertbuchard   File: run_FCN.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
   phase = "train"
   model_string = "final_fcn_model.h5"
   try:
      opts, args = getopt.getopt(argv,"hp:m:",["phase=","model="])
   except getopt.GetoptError:
      print('run_FCN.py -p <phase> -m <model>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('run_FCN.py -p <phase> -m <model>')
         sys.exit()
      elif opt in ("-p", "--phase"):
         phase = arg
      elif opt in ("-m", "--model"):
         model_string = arg
   return phase, model_string 
Example 28
Project: poloTrader   Author: GooTZ   File: run.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    mode = ''
    try:
        opts, args = getopt.getopt(argv,"m:h",["mode="])
    except getopt.GetoptError:
        print('run.py -m <TESTING/LIVE_TESTING/TRADING/FETCH_DATA>')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print('run.py -m <TESTING/LIVE_TESTING/TRADING/FETCH_DATA>')
            sys.exit()
        elif opt in ("-m", "--mode"):
            if arg in TradingMode.__members__:
                mode = TradingMode[arg]
            else:
                raise UnsupportedModeError(arg, "The given mode is not supported!")

    app.run(mode) 
Example 29
Project: azure-iot-sdk-python   Author: Azure   File: iothub_service_client_args.py    (license) View Source Project 6 votes vote down vote up
def get_iothub_opt(
        argv,
        connection_string,
        device_id):
    if len(argv) > 0:
        try:
            opts, args = getopt.getopt(
                argv, "hd:c:", [
                    "connectionstring=", "deviceid="])
        except getopt.GetoptError as get_opt_error:
            raise OptionError("Error: %s" % get_opt_error.msg)
        for opt, arg in opts:
            if opt == '-h':
                raise OptionError("Help:")
            elif opt in ("-c", "--connectionstring"):
                connection_string = arg
            elif opt in ("-d", "--deviceid"):
                device_id = arg

    if connection_string.find("HostName") < 0:
        raise OptionError(
            "Error: Hostname not found, not a valid connection string")

    return connection_string, device_id 
Example 30
Project: export-kobo   Author: pettarin   File: export_Kobo_notes_3.py    (license) View Source Project 6 votes vote down vote up
def read_command_line_parameters(argv):

    try:
        optlist, free = getopt.getopt(argv[1:], 'chtb:f:o:', ['book=', 'file=', 'output=', 'csv', 'help', 'titles'])
    #Python2#    except getopt.GetoptError, err:
    #Python3#
    except getopt.GetoptError as err:
        print_error(str(err))

    return dict(optlist)
### END read_command_line_parameters ###


### BEGIN usage ###
# usage()
# print script usage 
Example 31
Project: export-kobo   Author: pettarin   File: export_Kobo_notes.py    (license) View Source Project 6 votes vote down vote up
def read_command_line_parameters(argv):

    try:
        optlist, free = getopt.getopt(argv[1:], 'chtb:f:o:', ['book=', 'file=', 'output=', 'csv', 'help', 'titles'])
    #Python2#
    except getopt.GetoptError, err:
    #Python3#    except getopt.GetoptError as err:
        print_error(str(err))

    return dict(optlist)
### END read_command_line_parameters ###


### BEGIN usage ###
# usage()
# print script usage 
Example 32
Project: ivaochdoc   Author: ivaoch   File: base64.py    (license) View Source Project 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 33
Project: pytomo3d   Author: computational-seismology   File: util.py    (license) View Source Project 6 votes vote down vote up
def get_system_arg(argv, Usage):

    verbose = False
    parfile = None
    eventname = None

    opts, args = getopt.getopt(argv, "vp:h", ["parfile=", 'help', 'verbose'])
    for opt, value in opts:
        if opt in ("-p", "--parfile"):
            parfile = value
        elif opt in ("-v", "--verbose"):
            verbose = True
        elif opt in ("-h", "--help"):
            Usage()
            sys.exit()
        else:
            Usage()
            sys.exit()
    try:
        eventname = args[0]
    except:
        Usage()
        sys.exit()

    return eventname, verbose, parfile 
Example 34
Project: oss-github-analysis-project   Author: itu-oss-project-team   File: fetch_single_repo.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    owner = ""
    repo = ""
    force = False

    try:
        opts, args = getopt.getopt(argv, "o:r:f", ["owner=", "repo=", "force"])
    except getopt.GetoptError:
        print('ERROR in input arguments!')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':  # Help case
            print('fetch_repo.py -o <owner> -r <repo> -f Ex: fetch_repo.py --owner itu-oss-project-team  --repo oss-github-analysis-project --force')
            sys.exit()
        elif opt in ("-o", "--owner"):
            owner = arg
        elif opt in ("-r", "--repo"):
            repo = arg
        elif opt in ("-f", "--force"):
            force = True

    github_harvester = GitHubHarvester()

    #github_harvester.fetch_repo(owner, repo, force_fetch = force)
    github_harvester.fetch_repo('itu-oss-project-team', 'oss-github-analysis-project', force_fetch = True) 
Example 35
Project: mitogen   Author: dw   File: fakessh.py    (license) View Source Project 6 votes vote down vote up
def parse_args():
    hostname = None
    remain = sys.argv[1:]
    allopts = []
    restarted = 0

    while remain and restarted < 2:
        opts, args = getopt.getopt(remain, SSH_GETOPTS)
        remain = remain[:]  # getopt bug!
        allopts += opts
        if not args:
            break

        if not hostname:
            hostname = args.pop(0)
            remain = remain[remain.index(hostname) + 1:]

        restarted += 1

    return hostname, allopts, args 
Example 36
Project: cqut_student_schedule_py   Author: acbetter   File: cqut.py    (license) View Source Project 6 votes vote down vote up
def get_username_password(self):
        """??????? ????????"""
        try:
            opts, args = getopt.getopt(self.argv[1:], 'hu:p:', ['username=', 'password='])
        except getopt.GetoptError:
            self.logger.info('????????????????')
            self.logger.info('cqut.py -u <username> -p <password>')
            sys.exit(-1)
        for opt, arg in opts:
            if opt in ('-u', '--username'):
                self.username = arg
            elif opt in ('-p', '--password'):
                self.password = arg
        if self.username is None:
            self.username = input('???????: ')
        if self.password is None:
            self.password = input('???????: ') 
Example 37
Project: Intranet-Penetration   Author: yuxiaokui   File: webbrowser.py    (license) View Source Project 6 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)
    new_win = 0
    for o, a in opts:
        if o == '-n': new_win = 1
        elif o == '-t': new_win = 2
    if len(args) != 1:
        print >>sys.stderr, usage
        sys.exit(1)

    url = args[0]
    open(url, new_win)

    print "\a" 
Example 38
Project: Intranet-Penetration   Author: yuxiaokui   File: base64.py    (license) View Source Project 6 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)
    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': test1(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout)
    else:
        func(sys.stdin, sys.stdout) 
Example 39
Project: ICO-Moderator   Author: Plenglin   File: main.py    (license) View Source Project 6 votes vote down vote up
def get_args():

    keyargs, args = getopt.getopt(sys.argv[1:], 't:l:')
    out = {}

    if len(args) > 0:
        with open(args[0], 'r') as f:
            out = json.loads(f.read())
    elif len(keyargs) > 0:
        for k, arg in keyargs:
            if k == '-t':
                out['token'] = arg
            elif k == '-l':
                out['loglevel'] = int(arg)
    else:
        out = os.environ

    print(out)
    return out 
Example 40
Project: POEditor-Android-Translator   Author: JavonDavis   File: translate.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    option = ''
    try:
        opts, args = getopt.getopt(argv, "h:o:", ["option="])
    except getopt.GetoptError:
        print 'test.py -o <option[translate or build]>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -o <option[translate or build]>'
            sys.exit()
        elif opt in ("-o", "--option"):
            option = arg
    if option == 'translate':
        fname = str(raw_input("File name(Or absolute path to file if it is not in this directory):\n"))
        execute(fname)
    elif option == 'build':
        name_fname = str(raw_input("File name for csv containing string names(Or absolute path to file):\n"))
        values_fname = str(raw_input("File name for csv containing translation(Or absolute path to file):\n"))
        build_xml(name_fname, values_fname)
    else:
        print "Invalid option: " + option
        print "Option must be either translate or build" 
Example 41
Project: bifrost   Author: ledatelescope   File: like_bmon.py    (license) View Source Project 6 votes vote down vote up
def parseOptions(args):
    config = {}
    # Command line flags - default values
    config['args'] = []

    # Read in and process the command line flags
    try:
        opts, args = getopt.getopt(args, "h", ["help",])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage(exitCode=2)

    # Work through opts
    for opt, value in opts:
        if opt in ('-h', '--help'):
            usage(exitCode=0)
        else:
            assert False

    # Add in arguments
    config['args'] = args

    # Return configuration
    return config 
Example 42
Project: bifrost   Author: ledatelescope   File: getsiblings.py    (license) View Source Project 6 votes vote down vote up
def parseOptions(args):
    config = {}
    # Command line flags - default values
    config['args'] = []

    # Read in and process the command line flags
    try:
        opts, args = getopt.getopt(args, "h", ["help",])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage(exitCode=2)

    # Work through opts
    for opt, value in opts:
        if opt in ('-h', '--help'):
            usage(exitCode=0)
        else:
            assert False

    # Add in arguments
    config['args'] = args

    # Return configuration
    return config 
Example 43
Project: bifrost   Author: ledatelescope   File: like_ps.py    (license) View Source Project 6 votes vote down vote up
def parseOptions(args):
    config = {}
    # Command line flags - default values
    config['args'] = []

    # Read in and process the command line flags
    try:
        opts, args = getopt.getopt(args, "h", ["help",])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage(exitCode=2)

    # Work through opts
    for opt, value in opts:
        if opt in ('-h', '--help'):
            usage(exitCode=0)
        else:
            assert False

    # Add in arguments
    config['args'] = args

    # Return configuration
    return config 
Example 44
Project: bifrost   Author: ledatelescope   File: like_pmap.py    (license) View Source Project 6 votes vote down vote up
def parseOptions(args):
    config = {}
    # Command line flags - default values
    config['args'] = []
    
    # Read in and process the command line flags
    try:
        opts, args = getopt.getopt(args, "h", ["help",])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage(exitCode=2)
        
    # Work through opts
    for opt, value in opts:
        if opt in ('-h', '--help'):
            usage(exitCode=0)
        else:
            assert False
            
    # Add in arguments
    config['args'] = args
    
    # Return configuration
    return config 
Example 45
Project: bifrost   Author: ledatelescope   File: like_top.py    (license) View Source Project 6 votes vote down vote up
def parseOptions(args):
    config = {}
    # Command line flags - default values
    config['args'] = []

    # Read in and process the command line flags
    try:
        opts, args = getopt.getopt(args, "h", ["help",])
    except getopt.GetoptError, err:
        # Print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage(exitCode=2)
    # Work through opts
    for opt, value in opts:
        if opt in ('-h', '--help'):
            usage(exitCode=0)
        else:
            assert False

    # Add in arguments
    config['args'] = args

    # Return configuration
    return config 
Example 46
Project: MKFQ   Author: maojingios   File: webbrowser.py    (license) View Source Project 6 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)
    new_win = 0
    for o, a in opts:
        if o == '-n': new_win = 1
        elif o == '-t': new_win = 2
    if len(args) != 1:
        print >>sys.stderr, usage
        sys.exit(1)

    url = args[0]
    open(url, new_win)

    print "\a" 
Example 47
Project: MKFQ   Author: maojingios   File: base64.py    (license) View Source Project 6 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)
    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': test1(); return
    if args and args[0] != '-':
        with open(args[0], 'rb') as f:
            func(f, sys.stdout)
    else:
        func(sys.stdin, sys.stdout) 
Example 48
Project: DeepQA   Author: Conchylicultor   File: vec2bin.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
   inputfile = False
   outputfile = False
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print('vec2bin.py -i <inputfile> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('test.py -i <inputfile> -o <outputfile>')
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg

   if not inputfile or not outputfile:
       print('vec2bin.py -i <inputfile> -o <outputfile>')
       sys.exit(2)

   print('Converting %s to binary file format' % inputfile)
   vec2bin(inputfile, outputfile) 
Example 49
Project: true_review_web2py   Author: lucadealfaro   File: dict_diff.py    (license) View Source Project 6 votes vote down vote up
def main(argv):
    """Parse the arguments and start the main process."""
    try:
        opts, args = getopt.getopt(argv, "h", ["help"])
    except getopt.GetoptError:
        exit_with_parsing_error()
    for opt, arg in opts:
        arg = arg  # To avoid a warning from Pydev
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
    if len(args) == 2:
        params = list(get_dicts(*args))
        params.extend(get_dict_names(*args))
        compare_dicts(*params)
    else:
        exit_with_parsing_error() 
Example 50
Project: WikipediaQuiz   Author: NicholasMoser   File: wikipedia_quiz.py    (license) View Source Project 6 votes vote down vote up
def handle_args():
    """Handle the command line arguments provided for the program.
    There is an argument for the number of articles to make it configurable.
    There is also an argument for the length of the passage to make it configurable.
    If the argument is not provided it uses the provided default.
    """
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'n:l:', ['numberofarticles=', 'passagelength='])
    except getopt.GetoptError:
        print('wikipedia_quiz.py -n <numberofarticles> -l <passagelength>')
        logging.error('Opt error encountered')
        sys.exit(2)
    number_of_articles = NUMBER_OF_ARTICLES_DEFAULT
    passage_length = PASSAGE_LENGTH_DEFAULT
    for opt, arg in opts:
        if opt in ('-n', '--numberofarticles'):
            number_of_articles = int(arg)
            logging.info('Number of articles parameter found')
        elif opt in ('-l', '--passagelength'):
            passage_length = int(arg)
            logging.info('Passage length parameter found')
    return number_of_articles, passage_length