def main(): # Setup the command line arguments. optp = OptionParser() # Output verbosity options optp.add_option('-q', '--quiet', help='set logging to ERROR', action='store_const', dest='loglevel', const=logging.ERROR, default=logging.INFO) optp.add_option('-d', '--debug', help='set logging to DEBUG', action='store_const', dest='loglevel', const=logging.DEBUG, default=logging.INFO) optp.add_option('-v', '--verbose', help='set logging to COMM', action='store_const', dest='loglevel', const=5, default=logging.INFO) # Option for hash to download optp.add_option("-i", "--ioc", dest="ioc", help="The hash, ip, or domain of the ioc you want to check") opts, args = optp.parse_args() # Prompt if the user disn't give an ioc if opts.ioc is None: opts.ioc = raw_input("What's your IOC (Hash, ip, domain)? ") results = checkSS(opts.ioc) print results
def getProgOptions(): from optparse import OptionParser, make_option option_list = [ make_option("-i", "--in-seq", action="append", type="string",dest="inSeq"), make_option("-o", "--out-name", action="store", type="string",dest="outName"), make_option("-s", "--num-splits", action="store", type="int",dest="nSplits",default=3), make_option("-m", "--min-samp-count", action="store", type="int",dest="minSampCount",default=100), make_option("-t", "--max-samp-seq", action="store", type="int",dest="maxSampCountPerSeq"), make_option("-l", "--samp-len", action="store", type="int",dest="sampLen",default=1000), make_option("-f", "--samp-offset", action="store", type="int",dest="sampOffset",default=0), make_option("-d", "--make-other", action="store_true", dest="makeOther",default=False), make_option("-a", "--alphabet", action="store", type="choice",choices=("dna","protein"), dest="alphabet",default="dna"), make_option("-e", "--degen-len", action="store", type="int",dest="degenLen",default=1), ] parser = OptionParser(usage = "usage: %prog [options]",option_list=option_list) (options, args) = parser.parse_args() return options,args
def process_options(debugger_name, pkg_version, sys_argv, option_list=None): """Handle debugger options. Set `option_list' if you are writing another main program and want to extend the existing set of debugger options. The options dicionary from opt_parser is return. sys_argv is also updated.""" usage_str="""%prog [debugger-options] [python-script [script-options...]] Runs the extended python debugger""" # serverChoices = ('TCP','FIFO', None) optparser = OptionParser(usage=usage_str, option_list=option_list, version="%%prog version %s" % pkg_version) optparser.add_option("-F", "--fntrace", dest="fntrace", action="store_true", default=False, help="Show functions before executing them. " + "This option also sets --batch") optparser.add_option("--basename", dest="basename", action="store_true", default=False, help="Filenames strip off basename, " "(e.g. for regression tests)") optparser.add_option("--different", dest="different", action="store_true", default=True, help="Consecutive stops should have different " "positions") optparser.disable_interspersed_args() sys.argv = list(sys_argv) (opts, sys.argv) = optparser.parse_args() dbg_opts = {} return opts, dbg_opts, sys.argv
def main(): """Run the application from outside the module - used for deploying as frozen app""" import sys, os from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="msgpack", help="Open a dataframe as msgpack", metavar="FILE") parser.add_option("-p", "--project", dest="projfile", help="Open a dataexplore project file", metavar="FILE") parser.add_option("-i", "--csv", dest="csv", help="Open a csv file by trying to import it", metavar="FILE") parser.add_option("-t", "--test", dest="test", action="store_true", default=False, help="Run a basic test app") opts, remainder = parser.parse_args() if opts.test == True: app = TestApp() else: if opts.projfile != None: app = DataExplore(projfile=opts.projfile) elif opts.msgpack != None: app = DataExplore(msgpack=opts.msgpack) elif opts.csv != None: app = DataExplore() t = app.getCurrentTable() t.importCSV(opts.csv) else: app = DataExplore() app.mainloop()
def main(args=None): # parse the command line from optparse import OptionParser parser = OptionParser(description=__doc__) for key in choices: parser.add_option('--%s' % key, dest=key, action='store_true', default=False, help="display choices for %s" % key) options, args = parser.parse_args() # args are JSON blobs to override info if args: # lazy import import json for arg in args: if _os.path.exists(arg): string = file(arg).read() else: string = arg update(json.loads(string)) # print out choices if requested flag = False for key, value in options.__dict__.items(): if value is True: print '%s choices: %s' % (key, ' '.join([str(choice) for choice in choices[key]])) flag = True if flag: return # otherwise, print out all info for key, value in info.items(): print '%s: %s' % (key, value)
def _getArgs(): parser = OptionParser(usage="Train HTM Spatial Pooler") parser.add_option("-d", "--dataSet", type=str, default='randomSDR', dest="dataSet", help="DataSet Name, choose from sparse, correlated-input" "bar, cross, image") parser.add_option("-b", "--boosting", type=int, default=1, dest="boosting", help="Whether to use boosting") parser.add_option("-e", "--numEpochs", type=int, default=100, dest="numEpochs", help="number of epochs") parser.add_option("--spatialImp", type=str, default="cpp", dest="spatialImp", help="spatial pooler implementations: py, c++, or " "monitored_sp") (options, remainder) = parser.parse_args() print options return options, remainder
def main(argv=None): """Main entry point for the script""" ret_code = 0 if argv is None: argv = sys.argv parser = OptionParser() parser.add_option("-f", "--file", action="store", type="string", dest="filepath", default="/var/log/asterisk/refs", help="The full path to the refs file to process") (options, args) = parser.parse_args(argv) if not os.path.isfile(options.filepath): print("File not found: %s" % options.filepath, file=sys.stderr) return -1 try: process_file(options) except (KeyboardInterrupt, SystemExit, IOError): print("File processing cancelled", file=sys.stderr) return -1 return ret_code
def main(): """gterm-aware matplotlib demo""" setup() import matplotlib.pyplot as plt from optparse import OptionParser usage = "usage: %prog [--animate]" parser = OptionParser(usage=usage) parser.add_option("", "--animate", action="store_true", dest="animate", default=False, help="Simple animation demo") (options, args) = parser.parse_args() fmt = "png" if options.animate: plt.plot([1,2,3,2,3,1]) show(overwrite=False, format=fmt, title="Simple animation") n = 10 dx = 5.0/n for j in range(1,n): time.sleep(0.5) plt.plot([1,2,3,2,3,1+j*dx]) show(overwrite=True, format=fmt) else: plt.plot([1,2,3,2,3,0]) show(overwrite=False, format=fmt, title="Simple plot")
def make_cli_parser(): """ Creates the command line interface parser. """ usage = "\n".join([ """\ python %prog [OPTIONS] FASTAFILE1 FASTAFILE2 ... ARGUMENTS: FASTAFILE1, FASTAFILE2, ...: paths to one or more FASTA formatted files """, __doc__ ]) cli_parser = OptionParser(usage) cli_parser.add_option( '-o', '--outfile', default=OUTFILE_NAME, help="path to output file [Default: %default]" ) cli_parser.add_option( '-b', '--barrelon', action='store_true', help="ignore possible errors in parsing" ) return cli_parser
def setupParser(self, argv): usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option('-o', '--output-dir', action='store', dest='outputDir', default='./restdoc-output', help='The output directory for the API documentation files.') parser.add_option('-f', '--format', action='store', dest='format', default=0, help='The output format (MediaWiki). [Default: MediaWiki].') parser.add_option('-p', '--private-api', action='store_true', dest='privateApi', default=False, help='Generates private API documentation. [Default: False]') parser.add_option('-u', '--upload-documentation', action='store_true', dest='uploadDocumentation', default=False, help='Uploads the documentation to the Bitmunk wiki. ' + \ '[Default: False]') self.options, args = parser.parse_args(argv) largs = parser.largs return (self.options, args, largs)
def main(): parser = OptionParser(usage="%prog [options] jobfile|-", description=__doc__, version='%prog version 0.1') parser.add_option("-n", "--nb-procs", dest="nb_procs", type="int", default=DEFAULT_PROCESSES, help=("By default the number of concurent processes to " "run is equal to the number of CPUs " "(Default: %default)") ) (opts, spillover) = parser.parse_args() if len(spillover) != 1: parser.error('Invalid arguments.') if opts.nb_procs < 2: parser.error("There is no point of using that program if you are not " "running anything in parallel.") if spillover[0] == '-': jobfd = sys.stdin else: try: jobfd = open(spillover[0]) except IOError: parser.error("Job file '%s' open error" % spillover[0]) run_pexec(jobfd, opts.nb_procs)
def parse_options(): parser = OptionParser() parser.add_option("-f", "--file", dest="filename", default="/etc/sssd/sssd.conf", help="Set input file to FILE", metavar="FILE") parser.add_option("-o", "--outfile", dest="outfile", default=None, help="Set output file to OUTFILE", metavar="OUTFILE") parser.add_option("", "--no-backup", action="store_false", dest="backup", default=True, help="""Do not provide backup file after conversion. The script copies the original file with the suffix .bak by default""") parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Be verbose") (options, args) = parser.parse_args() if len(args) > 0: print >>sys.stderr, "Stray arguments: %s" % ' '.join([a for a in args]) return None # do the conversion in place by default if not options.outfile: options.outfile = options.filename return options
def main(argv=None): if argv is None: argv = sys.argv parser = OptionParser() parser.add_option("-k", "--key", dest="key", help="your Giant Bomb API key") opts, args = parser.parse_args() if opts.key is None: print >>sys.stderr, "Option --key is required" return 1 query = ' '.join(args) Bombject.api_key = opts.key search = GameResult.get('/search/').filter(resources='game') search = search.filter(query=query) if len(search.results) == 0: print "No results for %r" % query elif len(search.results) == 1: (game,) = search.results print "## %s ##" % game.name print print game.summary else: print "## Search results for %r ##" % query for game in search.results: print game.name return 0
def __init__(self, **kwargs): OptionParser.__init__(self, **kwargs) self.add_option("-m", "--masterMode", action="store_true", dest="masterMode", help="Run the script in master mode.", default=False) self.add_option("--noPrompts", action="store_true", dest="noPrompts", help="Uses default answers (intended for CLOUD TESTS only!).", default=False) self.add_option("--manifestFile", action="store", type="string", dest="manifestFile", help="A JSON file in the form of test_manifest.json (the default).") self.add_option("-b", "--browser", action="store", type="string", dest="browser", help="The path to a single browser (right now, only Firefox is supported).") self.add_option("--browserManifestFile", action="store", type="string", dest="browserManifestFile", help="A JSON file in the form of those found in resources/browser_manifests") self.add_option("--reftest", action="store_true", dest="reftest", help="Automatically start reftest showing comparison test failures, if there are any.", default=False) self.add_option("--port", action="store", dest="port", type="int", help="The port the HTTP server should listen on.", default=8080) self.add_option("--unitTest", action="store_true", dest="unitTest", help="Run the unit tests.", default=False) self.add_option("--fontTest", action="store_true", dest="fontTest", help="Run the font tests.", default=False) self.add_option("--noDownload", action="store_true", dest="noDownload", help="Skips test PDFs downloading.", default=False) self.add_option("--statsFile", action="store", dest="statsFile", type="string", help="The file where to store stats.", default=None) self.add_option("--statsDelay", action="store", dest="statsDelay", type="int", help="The amount of time in milliseconds the browser should wait before starting stats.", default=10000) self.set_usage(USAGE_EXAMPLE)
def __init__(self): gr.top_block.__init__(self) usage="%prog: [options] output_filename" parser = OptionParser(option_class=eng_option, usage=usage) parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("-r", "--sample-rate", type="eng_float", default=48000, help="set sample rate to RATE (48000)") parser.add_option("-N", "--nsamples", type="eng_float", default=None, help="number of samples to collect [default=+inf]") (options, args) = parser.parse_args () if len(args) != 1: parser.print_help() raise SystemExit, 1 filename = args[0] sample_rate = int(options.sample_rate) src = audio.source (sample_rate, options.audio_input) dst = gr.file_sink (gr.sizeof_float, filename) if options.nsamples is None: self.connect((src, 0), dst) else: head = gr.head(gr.sizeof_float, int(options.nsamples)) self.connect((src, 0), head, dst)
def ParseInputs(): global DOMAIN_PAIRS usage = """usage: %prog -d <domain> -u <admin_user> -p <admin_pass>\n""" parser = OptionParser() parser.add_option("-u", dest="admin_user", help="admin user") parser.add_option("-p", dest="admin_pass", help="admin pass") parser.add_option("-d", dest="domain", help="Domain name") parser.add_option("-n", dest="nick_domain", help="The domain of the nick that should exist.",) parser.add_option("--apply", action="store_true", dest="apply", help="""If present, changes will be applied, otherwise will run in dry run mode with no changes made""") (options, args) = parser.parse_args() if options.admin_user is None: print "-u (admin user) is required" sys.exit(1) if options.admin_pass is None: print "-p (admin password) is required" sys.exit(1) if (options.domain and not options.nick_domain) or (options.nick_domain and not options.domain): print "Both -d and -n need to be given" sys.exit(1) if not options.domain and not options.nick_domain and not DOMAIN_PAIRS: print "No domain pairs given" sys.exit(1) return options
def parse_options(): """ Options parser. """ parser = OptionParser(option_class=eng_option, usage="%prog: [options]") parser.add_option("-s", "--servername", type="string", default="localhost", help="Server hostname") (options, args) = parser.parse_args() return options
def main(): parser = OptionParser(usage="usage:%prog [options] filepath") parser.add_option("-p", "--port", action="store", type="string", default="", dest="port") (options, args) = parser.parse_args() port = options.port print port if not port: port = utils.config.get("global", "port") debug_mode = int(utils.config.get('global', 'debug')) sys.stderr.write("listen server on port %s ...\n" % port) settings = dict( debug=True if debug_mode else False, cookie_secret="e446976943b4e8442f099fed1f3fea28462d5832f483a0ed9a3d5d3859f==78d", session_secret="3cdcb1f00803b6e78ab50b466a40b9977db396840c28307f428b25e2277f1bcc", session_timeout=600, store_options={ 'redis_host': '127.0.0.1', 'redis_port': 6379, 'redis_pass': '', } ) application = HandlersApplication(handler, **settings) server = tornado.httpserver.HTTPServer(application) server.bind(port) server.start(1 if debug_mode else 15) tornado.ioloop.IOLoop.instance().start()
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option('-c', type='int', dest='concurrency', default=DEFAULT_CONCURRENCY, help='Number of multiple requests to make') parser.add_option('-s', type='int', dest='seconds', default=DEFAULT_SECONDS, help='Number of seconds to perform') parser.add_option("--mode", dest="mode", default=None) options, args = parser.parse_args() #run tests if 'test' == options.mode: test_parse_http_load_result() return if 1 != len(args): parser.print_help() return assert 1 <= options.concurrency <= 100 assert 1 <= options.seconds <= 100 #run bench old_sys_stderr = sys.stderr sys.stderr = StringIO() try: run_bench(args[0], options.seconds, options.concurrency) except Exception, e: print e import traceback print traceback.format_exc()
def __init__(self, **kwargs): OptionParser.__init__(self, **kwargs) self.add_option('--dz-url', action='store', dest='datazilla_url', default='https://datazilla.mozilla.org', metavar='str', help='datazilla server url (default: %default)') self.add_option('--dz-project', action='store', dest='datazilla_project', metavar='str', help='datazilla project name') self.add_option('--dz-branch', action='store', dest='datazilla_branch', metavar='str', help='datazilla branch name') self.add_option('--dz-key', action='store', dest='datazilla_key', metavar='str', help='oauth key for datazilla server') self.add_option('--dz-secret', action='store', dest='datazilla_secret', metavar='str', help='oauth secret for datazilla server') self.add_option('--sources', action='store', dest='sources', metavar='str', help='path to sources.xml containing project revisions')
def main(self,args=None): """ meant to be called if __name__ == '__main__': MyApplication().main() but lino.runscript calls it with args=sys.argv[:2] (command-line arguments are shifted by one) """ if args is None: args = sys.argv[1:] p = OptionParser( usage=self.usage, description=self.description) self.setupOptionParser(p) try: options,args = p.parse_args(args) self.applyOptions(options,args) return self.run(self.console) except UsageError,e: p.print_help() return -1
def cli_main(self,argv): with self: # so the sys.path was modified appropriately # I believe there's no performance hit loading these here when # CLI--it would load everytime anyway. from StringIO import StringIO from calibre.library import db from calibre_plugins.fanficfare_plugin.fanficfare.cli import main as fff_main from calibre_plugins.fanficfare_plugin.prefs import PrefsFacade from calibre.utils.config import prefs as calibre_prefs from optparse import OptionParser parser = OptionParser('%prog --run-plugin '+self.name+' -- [options] <storyurl>') parser.add_option('--library-path', '--with-library', default=None, help=_('Path to the calibre library. Default is to use the path stored in the settings.')) # parser.add_option('--dont-notify-gui', default=False, action='store_true', # help=_('Do not notify the running calibre GUI (if any) that the database has' # ' changed. Use with care, as it can lead to database corruption!')) pargs = [x for x in argv if x.startswith('--with-library') or x.startswith('--library-path') or not x.startswith('-')] opts, args = parser.parse_args(pargs) fff_prefs = PrefsFacade(db(path=opts.library_path, read_only=True)) fff_main(argv[1:], parser=parser, passed_defaultsini=StringIO(get_resources("fanficfare/defaults.ini")), passed_personalini=StringIO(fff_prefs["personal.ini"]))
def main () : usage = "./app/python/arc2warc.py [OPTIONS] ARC-FILES " parser = OptionParser(usage) parser.add_option("-c", "--compressed", dest="cmode", action="store_true", help="compressed outpout WARC FILE") parser.add_option("-t", "--tempdir", dest="tmpdir", help="Temporary working directory", default="./") parser.add_option("-v","--verbose", action="store_true",dest="verbose" , default=False, help="print more information") (options, args) = parser.parse_args() if not ( len (args) > 0 ): parser.error(" Please give one or more arcs to convert") for fname in args: ofname = guessname( fname , options.cmode ) if options.verbose: print 'Converting %s to %s' % ( fname , ofname ) convert( fname , ofname , options.tmpdir , options.cmode ) if options.verbose: print 'Done' return
def main(): os.chdir(os.path.dirname(os.path.realpath(__file__))) parser = OptionParser() parser.add_option( "-d", dest="debug", action="store_true", default=False, help="Enable debug mode (different starting board configuration)", ) parser.add_option("-t", dest="text", action="store_true", default=False, help="Use text-based GUI") parser.add_option("-o", dest="old", action="store_true", default=False, help="Use old graphics in pygame GUI") parser.add_option( "-p", dest="pauseSeconds", metavar="SECONDS", action="store", default=0, help="Sets time to pause between moves in AI vs. AI games (default = 0)", ) (options, args) = parser.parse_args() game = PythonChessMain(options) game.SetUp(options) game.MainLoop()
def main(): description = ( "This application generates .h and .ld files for symbols defined in input file. " "The input symbols file can be generated using nm utility like this: " "esp32-ulp-nm -g -f posix <elf_file> > <symbols_file>" ); parser = OptionParser(description=description) parser.add_option("-s", "--symfile", dest="symfile", help="symbols file name", metavar="SYMFILE") parser.add_option("-o", "--outputfile", dest="outputfile", help="destination .h and .ld files name prefix", metavar="OUTFILE") (options, args) = parser.parse_args() if options.symfile is None: parser.print_help() return 1 if options.outputfile is None: parser.print_help() return 1 with open(options.outputfile + ".h", 'w') as f_h, \ open(options.outputfile + ".ld", 'w') as f_ld, \ open(options.symfile) as f_sym: \ gen_ld_h_from_sym(f_sym, f_ld, f_h) return 0
def main(): p = OptionParser() options, args = p.parse_args() if len(args) != 1: p.error("no valid directory given") inp = args[0] outp = inp + ".npz" files = [] for dirpath, dirnames, filenames in os.walk(inp): for fn in filenames: if fn.endswith('.txt'): files.append( (dirpath[len(inp)+1:] + '/' + fn[:-4], os.path.join(dirpath, fn))) data = {} for key, fn in files: key = key.replace('/', '-').strip('-') try: data[key] = np.loadtxt(fn) except ValueError: print("Failed to load", fn) savez_compress(outp, **data)
def main(argv): """Flag options, automatically adds a -h/--help flag with this information.""" parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="read mountpoints from FILE", metavar="FILE") parser.add_option("-o", "--output", dest="output", help="dump drive information to FILE", metavar="FILE") parser.add_option("-p", "--prompt", dest="prompt", help="specify drive information before adding to database", action="store_true") parser.add_option("-l", "--location", dest="location", help="add hard drives to groups (boxes)", action="store_true") (options, args) = parser.parse_args() filename = options.filename try: if options.location: o = Organization() o.prompt() if filename == None: # default file to read drives from filename = "drives.in" #TODO: add username/password table username = raw_input("Enter username: "******"Enter username: "******"No file to read drives from. Please create a \'drives.in\' file to place the drives in, or specify a file with the -f flag."
def main(): atexit.register(fabric_cleanup, True) parser = OptionParser(usage="%prog RELEASE_DIR DESTINATION") (options, args) = parser.parse_args(sys.argv[1:]) comm_obj = _CommObj() if len(args) != 2: parser.print_help() sys.exit(-1) if not os.path.isdir(args[0]): print "release directory %s not found" % args[0] sys.exit(-1) destparts = args[1].split(':', 1) if len(destparts)==1: # it's a local release test area if not os.path.isdir(args[1]): _setup_local_release_dir(args[1]) comm_obj.put = shutil.copy comm_obj.put_dir = shutil.copytree comm_obj.run = local _push_release(args[0], args[1], comm_obj) else: # assume args[1] is a remote host:destdir comm_obj.put = put comm_obj.put_dir = put_dir comm_obj.run = run home = destparts[1] with settings(host_string=destparts[0]): _push_release(args[0], home, comm_obj)
def main(): PROG = os.path.basename(os.path.splitext(__file__)[0]) description = """Scan claims files""" parser = OptionParser(option_class=MultipleOption, usage='usage: %prog claims_file, claims_file, ...', version='%s %s' % (PROG, VERSION), description=description) if len(sys.argv) == 1: parser.parse_args(['--help']) args = parser.parse_args() p2k = {} k2p = {} try: with open('claimants.csv') as csv_file: for line in csv.reader(csv_file, dialect="excel"): p2k[line[0]] = line[1] k2p[line[1]] = line[0] except IOError: pass for filename in args[1]: with open(filename+'_masked.csv', 'wb') as cf: outfile = csv.writer(cf, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) analyze_file(filename, outfile, p2k, k2p) print len(p2k), len(k2p) with open('claimants.csv', 'wb') as cf: cout = csv.writer(cf, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for p in p2k: cout.writerow([p, p2k[p]])
def main(argv): optparse_usage = 'reaction_table.py -i <input_paths> -g <deltaG_path> -f <table_format> -r <root_dir>' parser = OptionParser(usage=optparse_usage) parser.add_option("-i", "--inputpaths", action="store", type="string", dest="input_path", help='The input file is the kegg_reaction.tsv') parser.add_option("-g", "--deltaGpaths", action="store", type="string", dest="deltaG_path", help='The input file is the Info_deltaG.csv') parser.add_option("-r", "--rootDir", action="store", type="string", dest="root_dir", help='The root directory. All files are generated here.') parser.add_option("-f", "--tableFormat", action="store", type="string", dest="format_path", help='The different number that you have given before.') (options, args) = parser.parse_args() if options.input_path: input_path = os.path.abspath(options.input_path) else: print 'Error: please provide proper input file name' if options.format_path: format_path = os.path.abspath(options.format_path) else: print 'Error: please provide proper input file name' if options.deltaG_path: deltaG_path = os.path.abspath(options.deltaG_path) else: print 'Error: please provide proper input file name' if options.root_dir: root_dir = os.path.abspath(options.root_dir) else: print 'ERROR: please provide proper root direcotory' # Run the funtion make_file(input_path,deltaG_path, format_path, root_dir)