Python optparse.OptionParser() Examples
The following are 30
code examples of optparse.OptionParser().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
optparse
, or try the search function
.
Example #1
Source File: semafor_evaluation.py From open-sesame with Apache License 2.0 | 7 votes |
def main(): e_parser = OptionParser() e_parser.add_option("--e_mode", dest="e_mode", type="choice", choices=["convert_conll_to_fe", "count_frame_elements", "compare_fefiles"], default="convert_conll_to_fe") e_parser.add_option("--conll_file", type="str", metavar="FILE") e_parser.add_option("--fe_file", type="str", metavar="FILE") e_parser.add_option("--fe_file_other", type="str", metavar="FILE") e_options, _ = e_parser.parse_args() if e_options.e_mode == "convert_conll_to_fe": assert e_options.conll_file and e_options.fe_file convert_conll_to_frame_elements(e_options.conll_file, e_options.fe_file) elif e_options.e_mode == "count_frame_elements": assert e_options.fe_file count_frame_elements(e_options.fe_file) elif e_options.e_mode == "compare_fefiles": assert e_options.fe_file and e_options.fe_file_other compare_fefiles(e_options.fe_file, e_options.fe_file_other)
Example #2
Source File: getmetrics_zipkin.py From InsightAgent with Apache License 2.0 | 6 votes |
def get_cli_config_vars(): """ get CLI options """ usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Enable verbose logging") parser.add_option("-t", "--testing", action="store_true", dest="testing", help="Set to testing mode (do not send data)." " Automatically turns on verbose logging") (options, args) = parser.parse_args() config_vars = dict() config_vars['testing'] = False if options.testing: config_vars['testing'] = True config_vars['logLevel'] = logging.INFO if options.verbose or options.testing: config_vars['logLevel'] = logging.DEBUG return config_vars
Example #3
Source File: delocate_fuse.py From delocate with BSD 2-Clause "Simplified" License | 6 votes |
def main(): parser = OptionParser( usage="%s WHEEL1 WHEEL2\n\n" % sys.argv[0] + __doc__, version="%prog " + __version__) parser.add_option( Option("-w", "--wheel-dir", action="store", type='string', help="Directory to store delocated wheels (default is to " "overwrite WHEEL1 input)")) parser.add_option( Option("-v", "--verbose", action="store_true", help="Show libraries copied during fix")) (opts, wheels) = parser.parse_args() if len(wheels) != 2: parser.print_help() sys.exit(1) wheel1, wheel2 = [abspath(expanduser(wheel)) for wheel in wheels] if opts.wheel_dir is None: out_wheel = wheel1 else: out_wheel = pjoin(abspath(expanduser(opts.wheel_dir)), basename(wheel1)) fuse_wheels(wheel1, wheel2, out_wheel)
Example #4
Source File: experiments.py From macops with Apache License 2.0 | 6 votes |
def ParseOptions(argv): """Parse command-line options.""" parser = optparse.OptionParser(usage='%prog [options]') parser.add_option('-D', '--debug', action='store_true', default=False) parser.add_option('-F', '--formatted', action='store_true', default=False, help=('Output experiments as one "experiment,status" ' 'per line')) parser.add_option( '-e', '--enable', action='store', dest='manually_enable', help='Comma-delimited list of experiments to manually enable.') parser.add_option( '-d', '--disable', action='store', dest='manually_disable', help='Comma-delimited list of experiments to manually enable.') parser.add_option( '-r', '--recommended', action='store', dest='recommended', help='Comma-delimited list of experiments to no longer manually manage.') opts, args = parser.parse_args(argv) return opts, args
Example #5
Source File: config.py From linter-pylama with MIT License | 6 votes |
def _expand_default(self, option): """Patch OptionParser.expand_default with custom behaviour This will handle defaults to avoid overriding values in the configuration file. """ if self.parser is None or not self.default_tag: return option.help optname = option._long_opts[0][2:] try: provider = self.parser.options_manager._all_options[optname] except KeyError: value = None else: optdict = provider.get_option_def(optname) optname = provider.option_attrname(optname, optdict) value = getattr(provider.config, optname, optdict) value = utils._format_option_value(optdict, value) if value is optparse.NO_DEFAULT or not value: value = self.NO_DEFAULT_VALUE return option.help.replace(self.default_tag, str(value))
Example #6
Source File: ez_setup.py From bugbuzz-python with MIT License | 6 votes |
def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) parser.add_option( '--version', help="Specify which version to download", default=DEFAULT_VERSION, ) options, args = parser.parse_args() # positional arguments are ignored return options
Example #7
Source File: arctic_list_libraries.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def main(): usage = """usage: %prog [options] [prefix ...] Lists the libraries available in a user's database. If any prefix parameters are given, list only libraries with names that start with one of the prefixes. Example: %prog --host=hostname rgautier """ setup_logging() parser = optparse.OptionParser(usage=usage) parser.add_option("--host", default='localhost', help="Hostname, or clustername. Default: localhost") (opts, args) = parser.parse_args() store = Arctic(opts.host) for name in sorted(store.list_libraries()): if (not args) or [n for n in args if name.startswith(n)]: print(name)
Example #8
Source File: arctic_enable_sharding.py From arctic with GNU Lesser General Public License v2.1 | 6 votes |
def main(): usage = """usage: %prog [options] arg1=value, arg2=value Enables sharding on the specified arctic library. """ setup_logging() parser = optparse.OptionParser(usage=usage) parser.add_option("--host", default='localhost', help="Hostname, or clustername. Default: localhost") parser.add_option("--library", help="The name of the library. e.g. 'arctic_jblackburn.lib'") (opts, _) = parser.parse_args() if not opts.library or '.' not in opts.library: parser.error('must specify the full path of the library e.g. arctic_jblackburn.lib!') print("Enabling-sharding: %s on mongo %s" % (opts.library, opts.host)) c = pymongo.MongoClient(get_mongodb_uri(opts.host)) credentials = get_auth(opts.host, 'admin', 'admin') if credentials: authenticate(c.admin, credentials.user, credentials.password) store = Arctic(c) enable_sharding(store, opts.library)
Example #9
Source File: pwiz.py From Quiver-alfred with MIT License | 6 votes |
def get_option_parser(): parser = OptionParser(usage='usage: %prog [options] database_name') ao = parser.add_option ao('-H', '--host', dest='host') ao('-p', '--port', dest='port', type='int') ao('-u', '--user', dest='user') ao('-P', '--password', dest='password', action='store_true') engines = sorted(DATABASE_MAP) ao('-e', '--engine', dest='engine', default='postgresql', choices=engines, help=('Database type, e.g. sqlite, mysql or postgresql. Default ' 'is "postgresql".')) ao('-s', '--schema', dest='schema') ao('-t', '--tables', dest='tables', help=('Only generate the specified tables. Multiple table names should ' 'be separated by commas.')) ao('-i', '--info', dest='info', action='store_true', help=('Add database information and other metadata to top of the ' 'generated file.')) ao('-o', '--preserve-order', action='store_true', dest='preserve_order', help='Model definition column ordering matches source table.') return parser
Example #10
Source File: main.py From llvm-zorg with Apache License 2.0 | 6 votes |
def action_runserver(name, args): """run a llvmlab instance""" import llvmlab from optparse import OptionParser, OptionGroup parser = OptionParser("%%prog %s [options]" % name) parser.add_option("", "--reloader", dest="reloader", default=False, action="store_true", help="use WSGI reload monitor") parser.add_option("", "--debugger", dest="debugger", default=False, action="store_true", help="use WSGI debugger") parser.add_option("", "--profiler", dest="profiler", default=False, action="store_true", help="enable WSGI profiler") (opts, args) = parser.parse_args(args) if len(args) != 0: parser.error("invalid number of arguments") app = llvmlab.ui.app.App.create_standalone() if opts.debugger: app.debug = True if opts.profiler: app.wsgi_app = werkzeug.contrib.profiler.ProfilerMiddleware( app.wsgi_app, stream = open('profiler.log', 'w')) app.run(use_reloader = opts.reloader, use_debugger = opts.debugger)
Example #11
Source File: command_line_parser.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
def __init__(self, sslyze_version: str) -> None: """Generate SSLyze's command line parser. """ self._parser = OptionParser(version=sslyze_version, usage=self.SSLYZE_USAGE) # Add generic command line options to the parser self._add_default_options() # Add plugin .ie scan command options to the parser scan_commands_group = OptionGroup(self._parser, "Scan commands", "") for option in self._get_plugin_scan_commands(): scan_commands_group.add_option(f"--{option.option}", help=option.help, action=option.action) self._parser.add_option_group(scan_commands_group) # Add the --regular command line parameter as a shortcut if possible self._parser.add_option( "--regular", action="store_true", dest=None, help=f"Regular HTTPS scan; shortcut for --{'--'.join(self.REGULAR_CMD)}", )
Example #12
Source File: do_tests.py From trelby with GNU General Public License v2.0 | 6 votes |
def main(): parser = optparse.OptionParser(version = "%%prog %s" % VERSION) parser.add_option("--file", dest="file", help="FILE to test") parser.add_option("--function", dest="func", help="FUNCTION to test") parser.add_option("--file-at-a-time", action="store_true", dest="faat", default = False, help="run tests from each file in the same" " process (faster, but coarser if tests fail)") (opts, args) = parser.parse_args() if opts.file: return doTest(opts) else: return doTests(opts) # returns a list of all function names from the given file that start with # "test".
Example #13
Source File: main.py From jawfish with MIT License | 6 votes |
def _getOptParser(self): import optparse parser = optparse.OptionParser() parser.prog = self.progName parser.add_option('-v', '--verbose', dest='verbose', default=False, help='Verbose output', action='store_true') parser.add_option('-q', '--quiet', dest='quiet', default=False, help='Quiet output', action='store_true') if self.failfast != False: parser.add_option('-f', '--failfast', dest='failfast', default=False, help='Stop on first fail or error', action='store_true') if self.catchbreak != False: parser.add_option('-c', '--catch', dest='catchbreak', default=False, help='Catch ctrl-C and display results so far', action='store_true') if self.buffer != False: parser.add_option('-b', '--buffer', dest='buffer', default=False, help='Buffer stdout and stderr during tests', action='store_true') return parser
Example #14
Source File: print_versions.py From esmlab with Apache License 2.0 | 6 votes |
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option( '-j', '--json', metavar='FILE', nargs=1, help='Save output as JSON into file, pass in ' "'-' to output to stdout", ) (options, args) = parser.parse_args() if options.json == '-': options.json = True show_versions(as_json=options.json) return 0
Example #15
Source File: ez_setup.py From feets with MIT License | 5 votes |
def _parse_args(): """Parse the command line for options.""" parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) parser.add_option( '--version', help="Specify which version to download", default=DEFAULT_VERSION, ) parser.add_option( '--to-dir', help="Directory to save (and re-use) package", default=DEFAULT_SAVE_DIR, ) options, args = parser.parse_args() # positional arguments are ignored return options
Example #16
Source File: portscan.py From pynmap with GNU General Public License v3.0 | 5 votes |
def parseArgs(): parser = OptionParser() parser.add_option("-t","--target",dest="target", help="IP Address to scan",metavar="127.0.0.1") parser.add_option("-p","--port range",dest="portrange", help="Port Range to scan separated with -",metavar="5-300 or 80") return parser
Example #17
Source File: pastee.py From instavpn with Apache License 2.0 | 5 votes |
def main(): parser = optparse.OptionParser() parser.add_option("-l", "--lexer", dest="lexer", metavar="LEXERNAME", help=("Force use of a particular lexer (i.e. c, py). " "This defaults to the extension of the supplied " "filenames, or 'text' if pasting from stdin.")) parser.add_option("-t", "--ttl", dest="ttl", metavar="DAYS", help="Number of days before the paste will expire.") parser.add_option("-k", "--key", dest="key", metavar="PASSPHRASE", help="Encrypt pastes with this key.") (options, filenames) = parser.parse_args() lexer = options.lexer key = options.key try: ttl = float(options.ttl) except ValueError: die_with_error("floating point number must be passed for TTL") except TypeError: ttl = None client = PasteClient() if filenames: # paste from multiple files for filename in filenames: print client.paste_file(filename, lexer=lexer, ttl=ttl, key=key) else: # paste from stdin print client.paste(sys.stdin.read(), lexer=lexer, ttl=ttl, key=key)
Example #18
Source File: mccabe.py From linter-pylama with MIT License | 5 votes |
def main(argv=None): if argv is None: argv = sys.argv[1:] opar = optparse.OptionParser() opar.add_option("-d", "--dot", dest="dot", help="output a graphviz dot file", action="store_true") opar.add_option("-m", "--min", dest="threshold", help="minimum complexity for output", type="int", default=1) options, args = opar.parse_args(argv) code = _read(args[0]) tree = compile(code, args[0], "exec", ast.PyCF_ONLY_AST) visitor = PathGraphingAstVisitor() visitor.preorder(tree, visitor) if options.dot: print('graph {') for graph in visitor.graphs.values(): if (not options.threshold or graph.complexity() >= options.threshold): graph.to_dot() print('}') else: for graph in visitor.graphs.values(): if graph.complexity() >= options.threshold: print(graph.name, graph.complexity())
Example #19
Source File: config.py From linter-pylama with MIT License | 5 votes |
def __init__(self, option_class, *args, **kwargs): optparse.OptionParser.__init__(self, option_class=Option, *args, **kwargs)
Example #20
Source File: ez_setup.py From iAI with MIT License | 5 votes |
def _parse_args(): """Parse the command line for options.""" parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package') parser.add_option( '--download-base', dest='download_base', metavar="URL", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) parser.add_option( '--version', help="Specify which version to download", default=DEFAULT_VERSION, ) parser.add_option( '--to-dir', help="Directory to save (and re-use) package", default=DEFAULT_SAVE_DIR, ) options, args = parser.parse_args() # positional arguments are ignored return options
Example #21
Source File: doctest_driver.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def main(): # Create the option parser. optparser = OptionParser(usage='%prog [options] NAME ...', version="Edloper's Doctest Driver, " "version %s" % __version__) action_group = OptionGroup(optparser, 'Actions (default=check)') action_group.add_options([CHECK_OPT, UPDATE_OPT, DEBUG_OPT]) optparser.add_option_group(action_group) reporting_group = OptionGroup(optparser, 'Reporting') reporting_group.add_options([VERBOSE_OPT, QUIET_OPT, UDIFF_OPT, CDIFF_OPT, NDIFF_OPT]) optparser.add_option_group(reporting_group) compare_group = OptionGroup(optparser, 'Output Comparison') compare_group.add_options([ELLIPSIS_OPT, NORMWS_OPT]) optparser.add_option_group(compare_group) # Extract optionflags and the list of file names. optionvals, names = optparser.parse_args() if len(names) == 0: optparser.error("No files specified") optionflags = (optionvals.udiff * REPORT_UDIFF | optionvals.cdiff * REPORT_CDIFF | optionvals.ellipsis * ELLIPSIS | optionvals.normws * NORMALIZE_WHITESPACE) # Perform the requested action. if optionvals.action == 'check': run(names, optionflags, optionvals.verbosity) elif optionvals.action == 'update': update(names, optionflags, optionvals.verbosity) elif optionvals.action == 'debug': debug(names, optionflags, optionvals.verbosity) else: optparser.error('INTERNAL ERROR: Bad action %s' % optionvals.action)
Example #22
Source File: ciscot7.py From ciscot7 with MIT License | 5 votes |
def main(): usage = "Usage: %prog [options]" parser = optparse.OptionParser(usage=usage) parser.add_option('-e', '--encrypt', action='store_true', dest='encrypt', default=False, help='Encrypt password') parser.add_option('-d', '--decrypt', action='store_true', dest='decrypt',default=True, help='Decrypt password. This is the default') parser.add_option('-p', '--password', action='store', dest="password", help='Password to encrypt / decrypt') parser.add_option('-f', '--file', action='store', dest="file", help='Cisco config file, only for decryption') options, args = parser.parse_args() render_as = "files" #fix issue 1, if encrypt is selected, that takes precedence if (options.encrypt): options.decrypt = False if (options.password is not None): if(options.decrypt): print("Decrypted password: " + decrypt_type7(options.password)) elif(options.encrypt): print("Encrypted password: " + encrypt_type7(options.password)) elif (options.file is not None): if(options.decrypt): try: f = open(options.file) regex = re.compile('(7 )([0-9A-Fa-f]+)($)') for line in f: result = regex.search(line) if(result): print("Decrypted password: " + decrypt_type7(result.group(2))) except IOError: print("Couldn't open file: " + options.file) elif(options.encrypt): parser.error("You can't encrypt a config file\nPlease run 'python ciscot7.py --help' for usage instructions.") else: parser.error("Password or config file is not specified!\nPlease run 'python ciscot7.py --help' for usage instructions.")
Example #23
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def cmdloop(self): parser = optparse.OptionParser() parser.add_option('-t', '--test', dest='test', action="store_true", help='Test against transcript(s) in FILE (wildcards OK)') (callopts, callargs) = parser.parse_args() if callopts.test: self.runTranscriptTests(callargs) else: if not self.run_commands_at_invocation(callargs): self._cmdloop()
Example #24
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 5 votes |
def print_help(self, *args, **kwargs): try: print (self._func.__doc__) except AttributeError: pass optparse.OptionParser.print_help(self, *args, **kwargs)
Example #25
Source File: cmd_args.py From pyscf with Apache License 2.0 | 5 votes |
def cmd_args(): ''' get input from cmdline ''' parser = optparse.OptionParser() parser.add_option('-v', '--verbose', action='store_false', dest='verbose', help='make lots of noise') parser.add_option('-q', '--quiet', action='store_false', dest='quite', default=False, help='be very quiet') parser.add_option('-o', '--output', dest='output', metavar='FILE', help='write output to FILE') parser.add_option('-m', '--max-memory', action='store', dest='max_memory', metavar='NUM', help='maximum memory to use (in MB)') (opts, args_left) = parser.parse_args() if opts.quite: opts.verbose = pyscf.lib.logger.QUIET if opts.verbose: opts.verbose = pyscf.lib.logger.DEBUG if opts.max_memory: opts.max_memory = float(opts.max_memory) return opts
Example #26
Source File: config.py From linter-pylama with MIT License | 5 votes |
def reset_parsers(self, usage='', version=None): # configuration file parser self.cfgfile_parser = configparser.ConfigParser(inline_comment_prefixes=('#', ';')) # command line parser self.cmdline_parser = OptionParser(Option, usage=usage, version=version) self.cmdline_parser.options_manager = self self._optik_option_attrs = set(self.cmdline_parser.option_class.ATTRS)
Example #27
Source File: getmetrics_datadog.py From InsightAgent with Apache License 2.0 | 5 votes |
def get_parameters(): usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-w", "--serverUrl", action="store", dest="serverUrl", help="Server Url") parser.add_option("-c", "--chunkLines", action="store", dest="chunkLines", help="Timestamps per chunk for historical data.") parser.add_option("-l", "--logLevel", action="store", dest="logLevel", help="Change log verbosity(WARNING: 0, INFO: 1, DEBUG: 2)") (options, args) = parser.parse_args() params = {} if options.serverUrl is None: params['serverUrl'] = 'https://app.insightfinder.com' else: params['serverUrl'] = options.serverUrl if options.chunkLines is None: params['chunkLines'] = 50 else: params['chunkLines'] = int(options.chunkLines) params['logLevel'] = logging.INFO if options.logLevel == '0': params['logLevel'] = logging.WARNING elif options.logLevel == '1': params['logLevel'] = logging.INFO elif options.logLevel >= '2': params['logLevel'] = logging.DEBUG return params
Example #28
Source File: getmetrics_jolokia.py From InsightAgent with Apache License 2.0 | 5 votes |
def getParameters(): usage = "Usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-d", "--directory", action="store", dest="homepath", help="Directory to run from") (options, args) = parser.parse_args() if options.homepath is None: homePath = os.getcwd() else: homePath = options.homepath return homePath
Example #29
Source File: arctic_delete_library.py From arctic with GNU Lesser General Public License v2.1 | 5 votes |
def main(): usage = """usage: %prog [options] Deletes the named library from a user's database. Example: %prog --host=hostname --library=arctic_jblackburn.my_library """ setup_logging() parser = optparse.OptionParser(usage=usage) parser.add_option("--host", default='localhost', help="Hostname, or clustername. Default: localhost") parser.add_option("--library", help="The name of the library. e.g. 'arctic_jblackburn.lib'") (opts, _) = parser.parse_args() if not opts.library: parser.error('Must specify the full path of the library e.g. arctic_jblackburn.lib!') print("Deleting: %s on mongo %s" % (opts.library, opts.host)) c = pymongo.MongoClient(get_mongodb_uri(opts.host)) db_name = opts.library[:opts.library.index('.')] if '.' in opts.library else None do_db_auth(opts.host, c, db_name) store = Arctic(c) store.delete_library(opts.library) logger.info("Library %s deleted" % opts.library)
Example #30
Source File: packet.py From vulscan with MIT License | 5 votes |
def main(): parser = OptionParser() parser.add_option("-s", "--src", dest="src", type="string", help="Source IP address", metavar="IP") parser.add_option("-d", "--dst", dest="dst", type="string", help="Destination IP address", metavar="IP") options, args = parser.parse_args() if options.dst is None: parser.print_help() sys.exit() else: dst_host = socket.gethostbyname(options.dst) if options.src is None: # Get the current Network Interface src_host = socket.gethostbyname(socket.gethostname()) else: src_host = options.src print("[+] Local Machine: %s" % src_host) print("[+] Remote Machine: %s" % dst_host) data = "TEST!!" print("[+] Data to inject: %s" % data) # IP Header ipobj = IP(src_host, dst_host) # TCP Header tcpobj = TCP(1234, 80) response = send(ipobj, tcpobj, iface="eth0", retry=1, timeout=0.3) if response: ip = ipobj.unpack(response) response = response[ip.ihl:] tcp = tcpobj.unpack(response) print "IP Header:", ip.list print "TCP Header:", tcp.list