Пример #1
0
def main(argv=None):
    import sys
    if argv is None:
        argv = sys.argv[1:]

    from optparse import OptionParser
    usage = "usage: %prog [options] <feed url>"
    parser = OptionParser(usage=usage)

    parser.add_option(
        "--schema", help="which news item type to create when scraping",
        default="local-news"
        )
    parser.add_option(
        "--http-cache", help='location to use as an http cache.  If a cached value is seen, no update is performed.', 
        action='store'
        )

    from ebpub.utils.script_utils import add_verbosity_options, setup_logging_from_opts
    add_verbosity_options(parser)

    options, args = parser.parse_args(argv)
    setup_logging_from_opts(options, logger)

    if len(args) < 1:
        parser.print_usage()
        sys.exit(0)

    scraper = LocalNewsScraper(url=args[0],  schema_slug=options.schema, http_cache=options.http_cache)

    scraper.update()
Пример #2
0
def main():
    usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option('-o', '--outfile', dest="outfile",
        help="Save stats to <outfile>", default=None)
    parser.add_option('-s', '--sort', dest="sort",
        help="Sort order when printing to stdout, based on pstats.Stats class",
        default=-1)

    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()
    sys.argv[:] = args

    if len(args) > 0:
        progname = args[0]
        sys.path.insert(0, os.path.dirname(progname))
        with open(progname, 'rb') as fp:
            code = compile(fp.read(), progname, 'exec')
        globs = {
            '__file__': progname,
            '__name__': '__main__',
            '__package__': None,
        }
        runctx(code, globs, None, options.outfile, options.sort)
    else:
        parser.print_usage()
    return parser
Пример #3
0
    def main():
        """
        Geocodes a location given on the command line.

        Usage:
            pygeocoder.py "1600 amphitheatre mountain view ca" [YOUR_API_KEY]
            pygeocoder.py 37.4219720,-122.0841430 [YOUR_API_KEY]

        When providing a latitude and longitude on the command line, ensure
        they are separated by a comma and no space.

        """
        usage = "usage: %prog [options] address"
        parser = OptionParser(usage, version=VERSION)
        parser.add_option("-k", "--key", dest="key", help="Your Google Maps API key")
        (options, args) = parser.parse_args()

        if len(args) != 1:
            parser.print_usage()
            sys.exit(1)

        query = args[0]
        gcoder = Geocoder(options.key)

        try:
            result = gcoder.geocode(query)
        except GeocoderError as err:
            sys.stderr.write('%s\n%s\nResponse:\n' % (err.url, err))
            json.dump(err.response, sys.stderr, indent=4)
            sys.exit(1)

        print(result)
        print(result.coordinates)
def parse_options():
    parser = OptionParser(usage="usage: %prog [options] <version>")
    parser.add_option("-f", "--from", dest="from_tag", metavar="FROM_TAG", help="The tag which should be used as start tag")
    parser.add_option("-t", "--to", dest="to_tag", metavar="TO_TAG", help="The tag which should be used as end tag")
    parser.add_option("-p", "--preview-url", dest="preview_url", metavar="PREVIEW_URL", 
                      help="The URL which is able to preview release notes")
    parser.add_option("-b", "--batch-mode", dest="batch_mode", action="store_true", default=False)
    (options, args) = parser.parse_args()
    
    if len(args) > 1:
        print __doc__
        parser.print_usage()
        sys.exit(1)
    
    current_tag = None
    try:
        current_tag = current_git_tag()
    except:
        current_tag = ""
    options.from_tag = options.from_tag or current_tag
    if options.from_tag is None:
        parser.error("Couldn't find start tag. Please specify one manually")
    options.to_tag = options.to_tag or "HEAD"
    
    options.preview_url = options.preview_url or os.getenv("PREVIEW_URL", PREVIEW_URL % nname(tool_config("name")))
    
    return (options, args)
Пример #5
0
def main():
    usage = "mactrace.py [-o output_file_path] scriptfile [arg] ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option('-o', '--outfile', dest="outfile",
                      help="Save trace to <outfile>", default=None)
    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()
    sys.argv[:] = args
    if options.outfile:
        twriter = TraceWriter(open(options.outfile, "w"))
    else:
        twriter = TraceWriter()
    sys.settrace(twriter.trace)
    if len(args) > 0:
        progname = args[0]
        sys.path.insert(0, os.path.dirname(progname))
        with open(progname, 'rb') as fp:
            code = compile(fp.read(), progname, 'exec')
        globs = {
            '__file__': progname,
            '__name__': '__main__',
            '__package__': None,
        }
        eval(code, globs)
    else:
        parser.print_usage()
    return parser
Пример #6
0
def main():

    option_parser = OptionParser(usage='%prog [options] input.xml, output.xml')
    option_parser.add_option('-s', '--start', type='float')
    option_parser.add_option('-e', '--end', type='float')
    option_parser.add_option('--src-start', '--os', type='float')
    option_parser.add_option('--src-end', '--oe', type='float')
    option_parser.add_option('-r', '--rate', type='float', default=1.0)
    option_parser.add_option('-v', '--verbose', action='count', default=0)
    option_parser.add_option('-f', '--farm', action='store_true')
    option_parser.add_option('-w', '--workers', type='int', default=20)
    option_parser.add_option('-a', '--advect', type='float', default=0.0)
    opts, args = option_parser.parse_args()

    if len(args) != 2:
        option_parser.print_usage()
        exit(1)


    res = schedule_retime(*args,
        src_start=opts.src_start,
        src_end=opts.src_end,
        dst_start=opts.start,
        dst_end=opts.end,
        sampling_rate=opts.rate,
        verbose=opts.verbose,
        farm=opts.farm,
        workers=opts.workers,
        advect=opts.advect
    )

    if opts.farm:
        print 'Qube job ID', res
Пример #7
0
class Attach():
	def __init__(self):
		self.git = Git()
		self.parser = OptionParser()
		self.parser.set_usage("mgit attach <subproject name>")

	def print_usage(self):
		self.parser.print_usage()

	def run(self, args):
		options, args = self.parser.parse_args(args[1:])
		if len(args) <= 0:
			self.parser.print_usage()
			return
	
		if len(args) > 1:
			module = args[1]
		else:
			module = self.git.module_name(args[0])
		if module == None or len(module) <= 0:
			return

		if not os.path.exists(module):
			print("module %s not exists." % module)
			return

		project = Project()
		project.append(module)
Пример #8
0
def main():
    import os, sys
    from optparse import OptionParser

    usage = "cProfile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option("-o", "--outfile", dest="outfile", help="Save stats to <outfile>", default=None)
    parser.add_option(
        "-s", "--sort", dest="sort", help="Sort order when printing to stdout, based on pstats.Stats class", default=-1
    )

    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()
    sys.argv[:] = args

    if len(sys.argv) > 0:
        sys.path.insert(0, os.path.dirname(sys.argv[0]))
        run("execfile(%r)" % (sys.argv[0],), options.outfile, options.sort)
    else:
        parser.print_usage()
    return parser
Пример #9
0
def main():
    usage = "usage: %prog [options] filename1 filename2"
    parser = OptionParser(usage=usage)

    parser.add_option("-r", "--relative-error", dest="relerr", default=0.0,
                      help="the maximum relative error")
    parser.add_option("-q", "--quiet",
                      action="store_true", dest="quiet", default=False,
                      help="don't print a line per numerical difference found")
    parser.add_option("-s", "--silent", action="store_true", dest="silent",
                      default=False, help="don't print anything"
                      " this is useful if you just want to use the exit status")
    
    (options, args) = parser.parse_args()

    if len(args) != 2:
        print "too few arguments"
        parser.print_usage()
        sys.exit(2)

    if options.silent:
        options.quiet = True

    same = ndiff(args[0], args[1], options.relerr, options.quiet)

    if same:
        sys.exit(0)
    else:
        sys.exit(1)
def parse_args():
    parser = OptionParser(description='Create a VM in oVirt from an existing VM Template')

    parser.add_option('--debug', action='store_true', 
        default=False, help='debug mode')

    parser.add_option('--api_host',
        default=None, help='oVirt API IP Address/Hostname')

    parser.add_option('--api_user',
        default=DEFAULT_API_USER, help='oVirt API Username, defaults to "%s"' % (DEFAULT_API_USER))

    parser.add_option('--api_pass',
        default=None, help='oVirt API Password')

    parser.add_option('--vm_template_name',
        default=None, help='VM template name to create VM from')

    parser.add_option('--cluster_name',
        default=None, help='Cluster name to create VM in')

    parser.add_option('--vm_name',
        default=None, help='VM name to be created')

    (opts, args) = parser.parse_args()

    for optname in ["api_host", "api_pass", "api_user", "vm_template_name", "cluster_name", "vm_name"]:
        optvalue = getattr(opts, optname)
        if not optvalue:
            parser.print_help()
            parser.print_usage()
            print "Please re-run with an option specified for: '%s'" % (optname)
            sys.exit(1)

    return opts
Пример #11
0
def cmd_line():
    parser = OptionParser()
    parser.set_usage("yum-debug-restore [options]")
    parser.add_option("-C", "--cache", action="store_true",
                      help="run from cache only")
    parser.add_option("-c", dest="conffile", help="config file location")
    parser.add_option("--enablerepo", action="append", dest="enablerepos",
                      help="specify additional repoids to query, can be specified multiple times")
    parser.add_option("--disablerepo", action="append", dest="disablerepos",
                      help="specify repoids to disable, can be specified multiple times")                      
    parser.add_option("-y", dest="assumeyes", action="store_true",
                      help="answer yes for all questions")
    parser.add_option("--skip-broken", action="store_true",
                      help="skip packages with depsolving problems")

    parser.add_option("--output", action="store_true",
                      help="output the yum shell commands")
    parser.add_option("--shell", 
                      help="output the yum shell commands to a file")

    parser.add_option("--install-latest", action="store_true",
                      help="install the latest instead of specific versions")
    parser.add_option("--ignore-arch", action="store_true",
                      help="ignore arch of packages, so you can dump on .i386 and restore on .x86_64")

    parser.add_option("--filter-types", 
                      help="Limit to: install, remove, update, downgrade")

    (opts, args) = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit(1)
    return (opts, args)
Пример #12
0
def main():
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__

    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    program_license = "Copyright 2014 Steven Hill Hendrix Lab Oregon State University     \
                Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
    program_longdesc = "Takes tabular blast output and fetches the raw reads from a paired fastq file. Supports interleaved paired end reads. Expects an index to be present that has the same prefix as the fastq file."

    argv = sys.argv[1:]
        # setup option parser
    parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
    parser.add_option("-b", "--blast", dest="blast", help="Tabular output from BLAST to a blastdb of raw reads.", metavar="FILE")
    parser.add_option("-t", "--num-threads", dest="num_threads", help="Number of threads to use when searching for reads.", metavar="INT")
    parser.add_option("-r", "--raw-reads", dest="reads", help="A single fastq file containing the source reads. If the reads are paired they should be interleaved.", metavar="FILE")
    # process options
    (opts, args) = parser.parse_args(argv)
    blast, rawReads, num_threads = opts.blast, opts.reads, int(opts.num_threads)

    if num_threads is None:
        num_threads = 1
    if blast is None or rawReads is None:
        parser.print_usage()
        sys.exit(-1)
    # MAIN BODY #
    toFind = {}
    print >> sys.stderr, "reading blast hits", "\r",
    readBlast(blast, toFind)
    print >> sys.stderr, "finding reads", "\r",
    findReads(rawReads, toFind, num_threads)
Пример #13
0
def main():
    log.addHandler(logging.StreamHandler())

    usage = """%prog SHP

SHP    World admin shapefile.
"""

    parser = OptionParser(usage=usage)
    parser.add_option(
        "-v", "--verbose", action="count", dest="verbose", help="Print verbose information for debugging.", default=0
    )
    parser.add_option("-q", "--quiet", action="count", dest="quiet", help="Suppress warnings.", default=0)
    parser.add_option(
        "-l", "--list", action="store_true", dest="dump", help="List countries as CSV of iso2, name.", default=None
    )

    (options, args) = parser.parse_args()
    args = [arg.decode(sys.getfilesystemencoding()) for arg in args]

    log_level = (logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG)[
        max(0, min(3, 1 + options.verbose - options.quiet))
    ]

    log.setLevel(log_level)

    if not len(args) == 1:
        parser.print_usage()
        sys.exit(1)

    (shp_path,) = args

    worldgeo(shp_path, options.dump)
Пример #14
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.allow_interspersed_args = False
    parser.add_option('-o', '--outfile', dest="outfile",
                      help="Save stats to <outfile>",
                      default='/tmp/profile.tmp')

    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()

    #viz = kcachegrind
    viz = profile_viz

    sys.path = [os.getcwd()] + sys.path

    if len(args) > 0:
        sys.argv[:] = args
        sys.path.insert(0, os.path.dirname(sys.argv[0]))
        viz('execfile(%r)' % sys.argv[0], out=options.outfile)
    else:
        parser.print_usage()
    return parser
Пример #15
0
def main():

    usage = "%prog [options] /path/to/error/file"

    parser = OptionParser(usage=usage)

    parser.add_option("-v", "--verbose",
                     action="store_true", dest="verbose", default=False,
                     help="print messages to stdout")

    (options, args) = parser.parse_args()

    if not len(args) > 0:
        parser.print_usage()
        quit(code=1)

    for file in args:
        fh = open(file)
        data = cPickle.load(fh)
        fh.close()

        for k in data.keys():
            print "%s: %s" % ( k, data[k])

    quit(code=0)
Пример #16
0
def main():
    """
    cmd executes a command on multiple hosts
    """
    p = OptionParser("python deploy_utils cmd [script] --hosts=[host1,host2]]")
    p.add_option('--verbose', action='store_true', dest='verbose', help='Verbose mode')
    p.add_option('--hosts', dest='hosts', help='Hosts')
    p.add_option('--ssh_key', dest='ssh_key', help='ssh key')
    p.add_option('--ssh_user', dest='ssh_user', help='ssh user')

    (options, args) = p.parse_args()
    args = args[1:]

    script = args[0]

    if not script or not options.hosts:
        p.print_usage()
        return 0

    env.user = options.ssh_user or os.environ.get('DEPLOY_UTILS_SSH_USER') or 'root'
    env.key_filename = options.ssh_key or os.environ.get('DEPLOY_UTILS_SSH_KEY')
    #env.rootpath = '/var/apps/'
    env.hosts = (options.hosts or '').split(',')

    with settings(warn_only=True,host_string=options.hosts):
        # Create the directory if needed.
        run('{0}'.format(script))
Пример #17
0
def main():
    """Main function code. Implementing:
        1. parsig args (-i, --in-file)
        2. iterating and transorming input data (results stored in table)
        3. printing out results in required format
    """
    parser = OptionParser(usage="usage: %prog [options] arg") 
    parser.add_option("-i", "--in-file", dest="in_filename", help="provide input data by specifing filename")
    (options, args) = parser.parse_args() 
    if options.in_filename is None:
        parser.print_usage()
        exit(0)
    results = []    
    for engines, phrases in gen_next_case(options.in_filename):
        engine_in_use = None
        score = 0
        if len(phrases) == 0:
            results.append(score)
            continue
        for i, phrase in enumerate(phrases):            
            if engine_in_use is None:
                engine_in_use = suggest(engines, phrases, exclude=phrases[0])
            elif engine_in_use == phrase:
                engine_in_use = suggest(engines, phrases[i:], exclude=engine_in_use)
                score += 1
        results.append(score)   
    for i, result in enumerate(results):    
        print "Case #%i: %i" % (i+1, result)
Пример #18
0
def parse_args():
    "Parse command line arguments"

    parser = OptionParser(usage=PARSER_USAGE)
    parser.add_option('-m', '--method', default='main',
                      help='Which parser method should be run')
    parser.add_option('-f', '--force', action="store_true",
                      help='Re-parse all data whether or not it has changed.')
    parser.add_option('-l', '--level', default='info',
                      help='Default logging level')
    parser.add_option('--disable-events', action='store_true', default=False,
                      help='Disable events processing')
    parser.add_option('--disable-indexing', action='store_true', default=False,
                      help='Disable synchronous indexing')
    parser.add_option('--congress',
                      help='Limit parsing to the specified congress')
    parser.add_option('--slow', action='store_true',
                      help='Slow down parsing so we don\'t interfere with other processes.')
    parser.add_option('--filter',
                      help='Only process files matching a regex.')
    kwargs, args = parser.parse_args()
    if not args:
        parser.print_usage()
        sys.exit()
    return kwargs, args
Пример #19
0
def main():
    log.addHandler(logging.StreamHandler())

    usage = """%prog CSV

CSV    CSV of missing country coordinates.
"""

    parser = OptionParser(usage=usage)
    parser.add_option("-v", "--verbose", action="count", dest="verbose",
                      help="Print verbose information for debugging.", default=0)
    parser.add_option("-q", "--quiet", action="count", dest="quiet",
                      help="Suppress warnings.", default=0)

    (options, args) = parser.parse_args()
    args = [arg.decode(sys.getfilesystemencoding()) for arg in args]

    log_level = (logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG,)[
        max(0, min(3, 1 + options.verbose - options.quiet))]

    log.setLevel(log_level)

    if not len(args) == 1:
        parser.print_usage()
        sys.exit(1)

    (csv_path, ) = args

    missinggeo(csv_path)
Пример #20
0
def main():
    # Argument parsing
    from optparse import OptionParser
    parser = OptionParser(
        usage = '%prog [options] <link> ...',
        description =
            'Shows a tree of link dependencies of the given EPICS pv link.')

    parser.add_option(
        '-m', '--nms',
        dest = 'check_ms', default = False, action = 'store_true',
        help = 'Check for missing maximise severity (MS) links')
    parser.add_option(
        '-q', '--quiet',
        dest = 'quiet', default = False, action = 'store_true',
        help = 'Only show errors, suppress normal output')
    parser.add_option(
        '-r', '--raw',
        dest = 'raw', default = dumb_terminal(), action = 'store_true',
        help = 'Print raw text without colour codes')
    parser.add_option(
        '-c', '--colour',
        dest = 'raw', action = 'store_false',
        help = 'Force colour coded output on unsupported destination')

    global options
    options, args = parser.parse_args()
    if args:
        for arg in args:
            follow_link(0, arg)
    else:
        parser.print_usage()
Пример #21
0
def parse_options():
    help = [
        'Usage: %prog [options] <command>',
        '',
        'Commands:',
    ]
    
    help.extend(['  %s' % c for c in Client.command_list()])
    
    parser = OptionParser( '\n'.join(help) )
    
    parser.add_option(
        '-v', '--verbose', dest='verbose', action='store_true',
        help='More verbose output',
    )
    
    parser.add_option(
        '--text_to_speech', dest='text_to_speech', action='store_true',
        help="Use the shell `say' command to enable text-to-speech for messages",
    )
    
    parser.add_option(
        '-l', '--live', dest='live', action='store_true',
        help='Use the "live" chat stream instead of transcript polling',
    )
    
    options, args = parser.parse_args()
    
    if not args:
        parser.print_usage()
        sys.exit(1)
    
    return options, args
Пример #22
0
def parse_command_line():
    usage = """%prog <mmfile> -o [<htmloutput>]
Create a FreeMind (.mm) document (see http://freemind.sourceforge.net/wiki/index.php/Main_Page)
the main node will be the title page and the lower nodes will be pages.
"""
    parser = OptionParser(usage)
    parser.add_option('-o', '--output', dest="outfile")
    parser.add_option('-m', '--minutes', dest="order_by_time",
        action='store_true',
        help="Order the minutes by time and show the time")
    (options, args) = parser.parse_args()
    if len(args) == 0:
        parser.print_usage()
        sys.exit(-1)

    infile = args[0]
    if not infile.endswith('.mm'):
        print "Input file must end with '.mm'"
        parser.print_usage()
        sys.exit(-1)

    outfile = sys.stdout
    if options.outfile:
        # Writing out the HTML in correct UTF-8 format is a little tricky.
        print "Outputting to '%s'" % (options.outfile)
        outfile = codecs.open(options.outfile, 'w', 'utf-8')

    mm2notes = Mm2Notes()
    lines = mm2notes.open(infile)
    mm2notes.set_order_by_time(options.order_by_time)

    mm2notes.write(outfile, lines)
Пример #23
0
def main(tester_lambda=None, pop_lambda=None, hlconfig_lambda=None, config_lambda=None):
  from optparse import OptionParser
  parser = OptionParser(usage="usage: sgatuner.py [options] Benchmark")
  parser.add_option("--check",
                    action="store_true", dest="check", default=False,
                    help="check for correctness")
  parser.add_option("--debug",
                    action="store_true", dest="debug", default=False,
                    help="enable debugging options")
  parser.add_option("-n", type="int", help="input size to train for")
  parser.add_option("--max_time",              type="float",  action="callback", callback=option_callback)
  parser.add_option("--rounds_per_input_size", type="int",    action="callback", callback=option_callback)
  parser.add_option("--mutations_per_mutator", type="int",    action="callback", callback=option_callback)
  parser.add_option("--output_dir",            type="string", action="callback", callback=option_callback)
  parser.add_option("--population_size",       type="int",    action="callback", callback=option_callback)
  parser.add_option("--min_input_size",        type="int",    action="callback", callback=option_callback)
  parser.add_option("--offset",                type="int",    action="callback", callback=option_callback)
  parser.add_option("--threads",               type="int",    action="callback", callback=option_callback)
  parser.add_option("--name",                  type="string", action="callback", callback=option_callback)
  parser.add_option("--abort_on",              type="string", action="callback", callback=option_callback)
  parser.add_option("--accuracy_target",       type="float",  action="callback", callback=option_callback)
  (options, args) = parser.parse_args()
  if len(args)!=1:
    parser.print_usage()
    sys.exit(1)
  if options.check:
    tunerconfig.applypatch(tunerconfig.patch_check)
  if options.debug:
    tunerconfig.applypatch(tunerconfig.patch_debug)
  if options.n:
    tunerconfig.applypatch(tunerconfig.patch_n(options.n))
  config.benchmark=args[0]
  if tester_lambda is None and pop_lambda is None and hlconfig_lambda is None:
    recompile()
  autotune(config.benchmark, None, tester_lambda, pop_lambda, hlconfig_lambda, config_lambda)
Пример #24
0
def main(args):
    parser = OptionParser(version='modifyrepo version %s' % __version__)
    # query options
    parser.add_option("--mdtype", dest='mdtype',
                      help="specific datatype of the metadata, will be derived from the filename if not specified")
    parser.add_option("--remove", action="store_true",
                      help="remove specified file from repodata")
    parser.add_option("--compress", action="store_true", default=True,
                      help="compress the new repodata before adding it to the repo (default)")
    parser.add_option("--no-compress", action="store_false", dest="compress",
                      help="do not compress the new repodata before adding it to the repo")
    parser.add_option("--compress-type", dest='compress_type',
                      help="compression format to use")
    parser.add_option("-s", "--checksum", dest='sumtype',
        help="specify the checksum type to use")
    parser.add_option("--unique-md-filenames", dest="unique_md_filenames",
        help="include the file's checksum in the filename, helps with proxies",
        action="store_true")
    parser.add_option("--simple-md-filenames", dest="unique_md_filenames",
        help="do not include the file's checksum in the filename",
        action="store_false")
    parser.usage = "modifyrepo [options] [--remove] <input_metadata> <output repodata>"
    
    (opts, argsleft) = parser.parse_args(args)
    if len(argsleft) != 2:
        parser.print_usage()
        return 0
    metadata = argsleft[0]
    repodir = argsleft[1]
    try:
        repomd = RepoMetadata(repodir)
    except MDError, e:
        print "Could not access repository: %s" % str(e)
        return 1
Пример #25
0
def parse_args():
    parser = OptionParser(description='Get the IP of a running VM')

    parser.add_option('--debug', action='store_true',
                      default=False, help='debug mode')

    parser.add_option('--api_host', default=None,
                      help='oVirt API IP Address/Hostname')

    parser.add_option(
        '--api_user', default=DEFAULT_API_USER,
        help='oVirt API Username, defaults to "%s"' % (DEFAULT_API_USER))

    parser.add_option('--api_pass', default=None, help='oVirt API Password')

    parser.add_option('--vm_id', default=None,
                      help='ID of an existing VM to add a disk to')

    (opts, args) = parser.parse_args()

    for optname in ["api_host", "api_pass", "api_user", "vm_id"]:
        optvalue = getattr(opts, optname)
        if not optvalue:
            parser.print_help()
            parser.print_usage()
            print "Please re-run with an option specified for: '%s'" % (optname)
            sys.exit(1)

    return opts
Пример #26
0
def main():
    """Handle command-line munging, and pass off control to the interesting
    stuff."""
    parser = OptionParser(
        usage='usage: %prog [options] <staging | prod>',
        description='Deploy a new version of DXR.')
    parser.add_option('-b', '--base', dest='base_path',
                      help='Path to the dir containing the builds, instances, '
                           'and deployment links')
    parser.add_option('-c', '--branch', dest='branch',
                      help='Deploy the revision from this branch which last '
                           'passed Jenkins.')
    parser.add_option('-p', '--python', dest='python_path',
                      help='Path to the Python executable on which to base the'
                           ' virtualenvs')
    parser.add_option('-e', '--repo', dest='repo',
                      help='URL of the git repo from which to download DXR. '
                           'Use HTTPS if possible to ward off spoofing.')
    parser.add_option('-r', '--rev', dest='manual_rev',
                      help='A hash of the revision to deploy. Defaults to the '
                           'last successful Jenkins build on the branch '
                           'specified by -c (or master, by default).')

    options, args = parser.parse_args()
    if len(args) == 1:
        non_none_options = dict((k, getattr(options, k)) for k in
                                (o.dest for o in parser.option_list if o.dest)
                                if getattr(options, k))
        Deployment(args[0], **non_none_options).deploy_if_appropriate()
    else:
        parser.print_usage()
Пример #27
0
def main():
    usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option("-o", "--outfile", dest="outfile", help="Save stats to <outfile>", default=None)
    parser.add_option(
        "-s", "--sort", dest="sort", help="Sort order when printing to stdout, based on pstats.Stats class", default=-1
    )

    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()

    if len(args) > 0:
        sys.argv[:] = args
        sys.path.insert(0, os.path.dirname(sys.argv[0]))
        fp = open(sys.argv[0])
        try:
            script = fp.read()
        finally:
            fp.close()
        run("exec(%r)" % script, options.outfile, options.sort)
    else:
        parser.print_usage()
    return parser
Пример #28
0
def parse_command_line():

    parser = OptionParser(
        usage = '%prog [options] uploaded.csv'
    )

    parser.add_option(
        '-o', '--output', dest='output_path', default='hist.csv',
        help='path to output CSV file',
    )

    parser.add_option(
        '-n', '--num-samples', dest='num_samples', default=None,
        help='maximum number of samples from input CSV',
    )

    parser.add_option(
        '-t', '--cluster-threshold', dest='cluster_thresh', default=25,
        help='number of photos per day considered significant when clustering',
    )

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.print_usage()
        sys.exit(1)

    return (options, args)
Пример #29
0
def main():
    log.addHandler(logging.StreamHandler())

    usage = """%prog SHP ISO_CSV BORDERS_CSV

SHP          World admin shapefile.
ISO_CSV      CSV of "ISO2, ISO3, ISON".
BORDERS_SWITCH_CSV  CSV of ISO2 codes of borders to switch.
BORDERS_DENY_CSV  CSV of ISO2 codes of borders to inhibit.
"""

    parser = OptionParser(usage=usage)
    parser.add_option("-v", "--verbose", action="count", dest="verbose",
                      help="Print verbose information for debugging.", default=0)
    parser.add_option("-q", "--quiet", action="count", dest="quiet",
                      help="Suppress warnings.", default=0)

    (options, args) = parser.parse_args()
    args = [arg.decode(sys.getfilesystemencoding()) for arg in args]

    log_level = (logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG,)[
        max(0, min(3, 1 + options.verbose - options.quiet))]

    log.setLevel(log_level)

    if not len(args) == 4:
        parser.print_usage()
        sys.exit(1)

    (shp_path, iso_csv_path, border_switch_csv_path, border_deny_csv_path) = args

    worldgeo(shp_path, iso_csv_path, border_switch_csv_path, border_deny_csv_path)
Пример #30
0
def main():
    from optparse import OptionParser
    usage = "yappi.py [-b] [-s] [scriptfile] args ..."
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = False
    parser.add_option("-b", "--builtins",
                  action="store_true", dest="profile_builtins", default=False,
                  help="Profiles builtin functions when set. [default: False]")
    parser.add_option("-s", "--single_thread",
                  action="store_true", dest="profile_single_thread", default=False,
                  help="Profiles only the thread that calls start(). [default: False]")
    if not sys.argv[1:]:
        parser.print_usage()
        sys.exit(2)

    (options, args) = parser.parse_args()
    sys.argv[:] = args

    if (len(sys.argv) > 0):
        sys.path.insert(0, os.path.dirname(sys.argv[0]))
        start(options.profile_builtins, not options.profile_single_thread)
        if sys.version_info >= (3, 0):
            exec(compile(open(sys.argv[0]).read(), sys.argv[0], 'exec'),
               sys._getframe(1).f_globals, sys._getframe(1).f_locals)
        else:
            execfile(sys.argv[0], sys._getframe(1).f_globals, sys._getframe(1).f_locals)
        stop()
        # we will currently use default params for these
        get_func_stats().print_all()
        get_thread_stats().print_all()
    else:
        parser.print_usage()