Пример #1
0
def Options():
    OptionList = [
        make_option("-f", "--offset", dest="PcdOffset", action="store", type="int",
                          help="Start offset to the image is used to store PCD value."),
        make_option("-u", "--value", dest="PcdValue", action="store",
                          help="PCD value will be updated into the image."),
        make_option("-t", "--type", dest="PcdTypeName", action="store",
                          help="The name of PCD data type may be one of VOID*,BOOLEAN, UINT8, UINT16, UINT32, UINT64."),
        make_option("-s", "--maxsize", dest="PcdMaxSize", action="store", type="int",
                          help="Max size of data buffer is taken by PCD value.It must be set when PCD type is VOID*."),
        make_option("-v", "--verbose", dest="LogLevel", action="store_const", const=EdkLogger.VERBOSE,
                          help="Run verbosely"),
        make_option("-d", "--debug", dest="LogLevel", type="int",
                          help="Run with debug information"),
        make_option("-q", "--quiet", dest="LogLevel", action="store_const", const=EdkLogger.QUIET,
                          help="Run quietly"),
        make_option("-?", action="help", help="show this help message and exit"),
    ]

    # use clearer usage to override default usage message
    UsageString = "%prog -f Offset -u Value -t Type [-s MaxSize] <input_file>"

    Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)
    Parser.set_defaults(LogLevel=EdkLogger.INFO)

    Options, Args = Parser.parse_args()

    # error check
    if len(Args) == 0:
        EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData=Parser.get_usage())

    InputFile = Args[len(Args) - 1]
    return Options, InputFile
Пример #2
0
def get_options():
	"""
	Returns a list of two elements, the first is an instance of optparse.Values (the command line options, like -v),
	and the second is an array of the remaining command line arguments.

	Expected command line arguments:
		depFilePath: The path of the DepFile to process. Must be specified.
		execution_arguments: Zero or more key=value strings that are evaluated in processing as values for <argument> tags.
		options: Application command line options.

	Examples:
		./program_name site.dep -v title=helloworld
		./program_name site.dep title=hello email=me@you.com -g -v
		./program_name site.dep -v
	"""

	global __default_config_file_path__

	option_parser = OptionParser(usage = "Usage: %prog depFilePath [execution_arguments] [options]")

	option_parser.set_defaults(version = False, help = False)

	option_parser.add_option("-c", "", dest = "config", default = __default_config_file_path__,
		help = "Path to the configuration file.")
	option_parser.add_option("", "--version", dest = "version", action = "store_true", default = False,
		help = "Retrieve version information.")
	option_parser.add_option("-q", "--quiet", dest = "quiet", action = "store_true", default = False,
		help = "Supress status messages.")

	return option_parser
Пример #3
0
def main():
    optparser = OptionParser()
    optparser.add_option(
            '-q', '--quiet',
            action='store_const', dest='verbosity', const=0,
            help="don't output anything to stderr")
    optparser.add_option(
            '-v', '--verbose',
            action='count', dest='verbosity',
            help="increase program verbosity")
    optparser.add_option(
            '-l', '--hostname',
            action='store', dest='hostname',
            help="hostname (or location) of this server")
    optparser.add_option(
            '-i', '--interface',
            action='store', dest='interface',
            help="interface (IP address) to bind to")
    optparser.add_option(
            '-p', '--port',
            action='store', dest='port', type='int',
            help="port number on which to listen")
    optparser.set_defaults(verbosity=1, hostname=None, interface='',
                           port=8000)
    (options, args) = optparser.parse_args()
    options = vars(options) # options is not a dict!?

    run(**options)
Пример #4
0
def main():
    """Build a shell and place it in the autoBisect cache."""

    usage = 'Usage: %prog [options]'
    parser = OptionParser(usage)
    parser.disable_interspersed_args()

    parser.set_defaults(
        buildOptions="",
    )

    # Specify how the shell will be built.
    # See buildOptions.py for details.
    parser.add_option('-b', '--build',
                      dest='buildOptions',
                      help='Specify build options, e.g. -b "--disable-debug --enable-optimize" ' +
                      '(python buildOptions.py --help)')

    parser.add_option('-r', '--rev',
                      dest='revision',
                      help='Specify revision to build')

    options = parser.parse_args()[0]
    options.buildOptions = buildOptions.parseShellOptions(options.buildOptions)

    with LockDir(getLockDirPath(options.buildOptions.repoDir)):
        if options.revision:
            shell = CompiledShell(options.buildOptions, options.revision)
        else:
            localOrigHgHash = hgCmds.getRepoHashAndId(options.buildOptions.repoDir)[0]
            shell = CompiledShell(options.buildOptions, localOrigHgHash)

        obtainShell(shell, updateToRev=options.revision)
        print shell.getShellCacheFullPath()
Пример #5
0
def main():
    optparser = OptionParser("usage: %prog [options] inputdir1 inputdir2 etc")
    optparser.set_defaults(outputdir="out",
                           outputfile="parsed.json", 
                           extension=".js",
                           version=""
                           )
    optparser.add_option( "-o", "--outputdir",
                          action="store", dest="outputdir", type="string",
                          help="Directory to write the parser results" )
    optparser.add_option( "-f", "--file",
                          action="store", dest="outputfile", type="string",
                          help="The name of the file to write the JSON output" )
    optparser.add_option( "-e", "--extension",
                          action="store", dest="extension", type="string",
                          help="The extension for the files that should be parsed" )
    optparser.add_option( "-v", "--version",
                          action="store", dest="version", type="string",
                          help="The version of the project" )
    (opts, inputdirs) = optparser.parse_args()
    if len(inputdirs) > 0:
        docparser = DocParser( inputdirs, 
                            opts.outputdir, 
                            opts.outputfile, 
                            opts.extension,
                            opts.version
                            )
    else:
        optparser.error("Incorrect number of arguments")
Пример #6
0
def get_options():
    """Get options for command line interface to update_cmd_states.
    """
    from optparse import OptionParser
    parser = OptionParser()
    parser.set_defaults()
    parser.add_option("--dbi",
                      default='sqlite',
                      help="Database interface (sqlite|sybase)")
    parser.add_option("--server",
                      default='db_base.db3',
                      help="DBI server (<filename>|sybase)")
    parser.add_option("--user",
                      help="sybase user (default=Ska.DBI default)")
    parser.add_option("--database",
                      help="sybase database (default=Ska.DBI default)")
    parser.add_option("--mp_dir",
                      default='/data/mpcrit1/mplogs',
                      help="MP load directory")
    parser.add_option("--h5file",
                      default='cmd_states.h5',
                      help="filename for HDF5 version of cmd_states")
    parser.add_option("--datestart",
                      help="Starting date for update (default=Now-10 days)")
    parser.add_option("--loglevel",
                      type='int',
                      default=20,
                      help='Log level (10=debug, 20=info, 30=warnings)')
    parser.add_option("--occ",
                      action='store_true',
                      help="Running on the OCC GRETA network")

    (opt, args) = parser.parse_args()
    return (opt, args)
Пример #7
0
def get_options():
	# Today's datetime
	today = dict()
	today['datetime'] = datetime.now()
	today['api_date'] = today['datetime'].strftime('%Y%m%d')

	#yesterday's datetime
	yesterday = dict()
	yesterday['datetime'] = datetime.now() - timedelta(days=1)
	yesterday['api_date'] = yesterday['datetime'].strftime('%Y%m%d')

	# Get command-line options
	parser = OptionParser()
	parser.add_option("-v", action="store_true", dest="verbose")
	parser.add_option("-q", action="store_false", dest="verbose")
	parser.add_option("--runSim", action="store_true", dest="run_sim")

	parser.set_defaults(verbose=False,
		run_sim=False)

	(options, args) = parser.parse_args()

	# Create an error list to identify errors
	errors = list()

	if errors:
	    parser.error("\n".join(errors))

	return (options,args)
Пример #8
0
def init():
  "Get input options."
  global opts

  "Setup program input options."
  parser = OptionParser(version = "%prog 1.0.0")
  parser.add_option("-v", "--verbose", action="store_true", dest = "verbose",
    help = "verbose mode [%default]")
  parser.add_option("-g", "--debug", action="store_true", dest = "debug",
    help = "debug mode [%default]")
  parser.add_option("-F", "--foreground", action="store_true",
    dest = "foreground", help = "run in foreground [%default]")
  parser.add_option("-r", "--disable-raid", action="store_false",
    dest = "raid", help = "disable RAID monitoring")
  parser.add_option("-n", "--disable-nagios", action="store_false",
    dest = "nagios", help = "disable nagios monitoring")
  parser.add_option("-H", "--host", dest = "host",
    help = "LCD daemon hostname or IP address [%default]")
  parser.add_option("-p", "--port", dest = "port",
    help = "LCD daemon port number [%default]")
  parser.add_option("-i", "--interval", dest = "interval",
    help = "refresh value in seconds [%default]")
  parser.add_option("-N", "--nagiostats", dest = "nagiostats",
    help = "full path to nagiostats binary [%default]")
  parser.set_defaults(help = False, verbose = False, debug = False,
    foreground = False, raid = True, nagios = True,
    host = "localhost", port = 13666, interval = 1,
    nagiostats = "/usr/sbin/nagiostats")
  (opts, args) = parser.parse_args()
  if not opts.raid and not opts.nagios:
    err("cannot disable both raid and nagios, something's gotta' give'")
Пример #9
0
def _parse_options():
    usage = "Usage: %prog [options]"
    parser = OptionParser(usage)
    parser.set_defaults(debug=False)
    parser.add_option("-d", "--debug", action="store_true", dest="debug")
    global options
    (options, args) = parser.parse_args()
Пример #10
0
def parse_options(args):
    from optparse import OptionParser

    description = ("Merge peak calls from BED regions")
    usage = '%prog [options] BEDFILES...'
    version = '%%prog %s' % __version__

    parser = OptionParser(usage=usage, version=version,
                          description=description)

    parser.add_option("-m", "--minimum-replicated",
        action="store", type='int', dest="min_rep",
        help="minimum times a base is in a peak [default: %default]")

    parser.add_option("-v", "--verbose",
        action="store_true", dest="verbose",
        help="maximum verbosity [default: %default]")

    parser.set_defaults(min_rep=2,
                        verbose=False)

    options, args = parser.parse_args()

    if len(args) < 2:
        parser.error('specify at least 2 BEDFILES')

    return options, args
Пример #11
0
def parse_options():
    from optparse import OptionParser
    opt_parser = OptionParser(usage=usage)
    opt_parser.add_option("-l", "--list",
                          action="store", type="string", dest="list",
                          help="Target list to which all specified tasks will be moved.")
    opt_parser.add_option("-f", "--filter",
                          action="store", type="string", dest="filter",
                          help="Data filter (RTM query syntax)")
    opt_parser.add_option("-v", "--verbose",
                          action="store_true", dest="verbose",
                          help="Print diagnostic messages")
    opt_parser.add_option("-d", "--dry-run",
                          action="store_true", dest="dry_run",
                          help="Don't execute any updates, just check input and (if verbose) print planned actions")
    opt_parser.add_option("-g", "--debug",
                          action="store_true", dest="debug",
                          help="Print debugging information")
                          
    opt_parser.set_defaults(verbose = False, dry_run = False, debug=False,
                            add =[], remove =[])
    (opts, args) = opt_parser.parse_args()

    if not opts.filter:
        opt_parser.error("--filter not specified")
    if not opts.list:
        opt_parser.error("--list not specified")

    if opts.debug:
        import logging
        logging.basicConfig(level = logging.DEBUG)

    return opts
Пример #12
0
def run( arguments ):
    usage = USAGE.strip()
    parser = OptionParser( usage=usage )
    options = dict(
        count=10,
        header=False,
        interactive=False,
        user='',
        password='',
    )
    parser.set_defaults( **options )
    parser.add_option( '-l', '--last', dest='count', help='Show only the last number of posts.' )
    parser.add_option( '-e', '--header', action='store_true', help='Show column headers. Hidden by default.' )
    parser.add_option( '-i', '--interactive', action='store_true', help='Prompt for missing credentials when connecting to the server.' )
    parser.add_option( '-u', '--user' )
    parser.add_option( '-p', '--password' )
    options, arguments = parser.parse_args( arguments )
    if len( arguments ) > 1:
        raise RuntimeError, 'Unexpected arguments: %s' % ' '.join( arguments )
    url = arguments[0] if arguments else ''
    listPosts(
        url,
        count=int( options.count or 0 ),
        header=options.header,
        user=options.user,
        password=options.password,
        interactive=options.interactive,
    )
Пример #13
0
def main(argv):
    op = OptionParser(usage=USAGE, description=DESCRIPTION)
    op.disable_interspersed_args()
    op.add_option(
        "--ccache",
        help="location of ccache (default: %s)" % DEFAULT_CCACHE)
    op.add_option(
        "--compression",
        help="use compression",
        action="store_true")
    op.add_option(
        "-d", "--directory",
        help="where to create the temporary directory with the cache and" \
             " other files (default: %s)" \
            % DEFAULT_DIRECTORY)
    op.add_option(
        "--hardlink",
        help="use hard links",
        action="store_true")
    op.add_option(
        "-n", "--times",
        help="number of times to compile the file (default: %d)" \
            % DEFAULT_TIMES,
        type="int")
    op.add_option(
        "-v", "--verbose",
        help="print progress messages",
        action="store_true")
    op.set_defaults(
        ccache=DEFAULT_CCACHE,
        directory=DEFAULT_DIRECTORY,
        times=DEFAULT_TIMES)
    (options, args) = op.parse_args(argv[1:])
    if len(args) < 2:
        op.error("Missing arguments; pass -h/--help for help")

    global verbose
    verbose = options.verbose

    options.ccache = abspath(options.ccache)

    compiler = find_in_path(args[0])
    if compiler is None:
        op.error("Could not find %s in PATH" % args[0])
    if "ccache" in basename(realpath(compiler)):
        op.error(
            "%s seems to be a symlink to ccache; please specify the path to"
            " the real compiler instead" % compiler)

    print "Compilation command: %s -c -o %s.o" % (
        " ".join(args),
        splitext(argv[-1])[0])
    print "Compression:", on_off(options.compression)
    print "Hardlink:", on_off(options.hardlink)

    tmp_dir = "%s/perfdir.%d" % (abspath(options.directory), getpid())
    recreate_dir(tmp_dir)
    result = test(tmp_dir, options, args[:-1], args[-1])
    rmtree(tmp_dir)
    print_result(result)
Пример #14
0
def get_parser_instance(defaults=None):
    p = OptionParser()
    unimp_group=OptionGroup(p, "Unimplimented options",
        "These options do NOT work yet, they will be accepted and ignored.")

    p.add_option("--outputdir", "-d", dest="outputdir", type="string",
                help="Directory to put the encoded file in")
    p.add_option("--config", "-c", dest="configfile", type="string")
    p.add_option("--audiobitrate", "-a", dest="abr", type="string")
    unimp_group.add_option("--hostname", "-H", dest="hostname", type="string",
                help="hostname for the backend to connect to. This is"+
                     " being ignored for the moment")
    unimp_group.add_option("--port", "-p", dest="portnumber", type="int",
                help="Port to connect or listen on")
    unimp_group.add_option("--debug", "-D", dest="debug", action="count")
    #long only options
    #p.add_option("--ignore-defaults", dest="config", type="string")
    p.add_option("--crf", dest="crf", type="string",
                 help="which x264 CRF number to use. default:22")
    unimp_group.add_option("--threads", dest="threads", type="string",
                           help="number of threads to use. default auto")
    p.add_option_group(unimp_group)
    if not defaults is None:
        if type(defaults) == type(dict()):
            p.set_defaults(**defaults)
    return p
Пример #15
0
def ParseOptions():
  """Parse the command line options.

  @return: (options, args) as from OptionParser.parse_args()

  """
  parser = OptionParser(description="Ganeti cluster watcher",
                        usage="%prog [-d]",
                        version="%%prog (ganeti) %s" %
                        constants.RELEASE_VERSION)

  parser.add_option(cli.DEBUG_OPT)
  parser.add_option(cli.NODEGROUP_OPT)
  parser.add_option("-A", "--job-age", dest="job_age", default=6 * 3600,
                    help="Autoarchive jobs older than this age (default"
                          " 6 hours)")
  parser.add_option("--ignore-pause", dest="ignore_pause", default=False,
                    action="store_true", help="Ignore cluster pause setting")
  parser.add_option("--wait-children", dest="wait_children",
                    action="store_true", help="Wait for child processes")
  parser.add_option("--no-wait-children", dest="wait_children",
                    action="store_false",
                    help="Don't wait for child processes")
  # See optparse documentation for why default values are not set by options
  parser.set_defaults(wait_children=True)
  options, args = parser.parse_args()
  options.job_age = cli.ParseTimespec(options.job_age)

  if args:
    parser.error("No arguments expected")

  return (options, args)
Пример #16
0
def parse_options():
    parser = OptionParser()
    parser.add_option(
        "-a", "--ampfile", dest="ampsname", metavar="AMP", help="single input .amp file (default: %default)"
    )
    parser.add_option(
        "-s", "--segfile", dest="segsname", metavar="SEG", help="single input .seg file (default: %default)"
    )
    parser.add_option(
        "-w", "--wavfile", dest="wavname", metavar="WAV", help="single input .wav file (default: %default)"
    )

    group = OptionGroup(parser, "Batch processing")
    group.add_option(
        "-i",
        "--input-dir",
        dest="indir",
        help="input directory; must contain wav/ and amps/ subdirectories" " with matching filesets.",
    )
    group.add_option("-o", "--output-dir", dest="outdir", help="output directory (will be created if it doesn't exist)")
    parser.add_option_group(group)

    parser.set_defaults(ampsname="test.amp", segsname="test.seg", wavname="test.wav")

    return parser.parse_args()
Пример #17
0
def _make_optparser():
    parser = OptionParser(
        description="Dumps the NAV PostgreSQL database as plain-text SQL to "
                    "stdout, with optional data filtering.",
        version=buildconf.VERSION,
        epilog="The output of the program can be inserted into an empty "
               "PostgreSQL database using the psql program."
    )
    parser.set_defaults(
        filters={},
        exclude=[],
    )

    opt = parser.add_option
    opt("-e", "--exclude", action="append", type="string", dest="exclude",
        metavar="TABLE", help="Exclude TABLE data from dump")
    opt("-c", "--only-open-cam", action="store_true", dest="only_open_cam",
        help="Only dump open CAM records")
    opt("-a", "--only-open-arp", action="store_true", dest="only_open_arp",
        help="Only dump open ARP records")
    opt("-f", "--filter", type="string",
        action="callback", callback=_add_filter,
        metavar="FILTER", help="Filter a table's contents. "
                               "FILTER must match "
                               "<tablename>=<SQL where clause>")
    return parser
Пример #18
0
def parseArgs():
    """Parse command-line args and return options object.
    returns: opts parse options dict"""
    desc = ( 'Pyretic runtime' )
    usage = ( '%prog [options]\n'
              '(type %prog -h for details)' )
    
    end_args = 0
    for arg in sys.argv[1:]:
        if not re.match('-',arg):
            end_args = sys.argv.index(arg)
    kwargs_to_pass = None
    if end_args > 0:
        kwargs_to_pass = sys.argv[end_args+1:]
        sys.argv = sys.argv[:end_args+1]

    op = OptionParser( description=desc, usage=usage )
    op.add_option( '--frontend-only', '-f', action="store_true", 
                     dest="frontend_only", help = 'only start the frontend'  )
    op.add_option( '--mode', '-m', type='choice',
                     choices=['interpreted','i','reactive0','r0'], 
                     help = '|'.join( ['interpreted/i','reactive0/r0'] )  )
    op.add_option( '--verbosity', '-v', type='choice',
                     choices=['low','normal','high'], default = 'low',
                     help = '|'.join( ['quiet','high'] )  )

    op.set_defaults(frontend_only=False,mode='reactive0')
    options, args = op.parse_args()

    return (op, options, args, kwargs_to_pass)
Пример #19
0
def get_command_line_options(executable_name, arguments):
    parser = OptionParser(usage="%s options" % executable_name)
    parser.set_defaults(port = 9876)
    parser.add_option("-x", "--xmlrpc", action="store_true", dest="xml", help="Start XMLRPC StatServer")
    parser.add_option("-n", "--npipe", action="store_true", dest="pipe", help="Start named pipe StatServer")
    parser.add_option("-o", "--out", type="string", dest="output", help="Output DB File")
    
    xml_group = OptionGroup(parser, "Options for XMLRPC Server")
    xml_group.add_option("-p", "--port", type="string", dest="port", help="port to run the server")

    parser.add_option_group(xml_group)

    pipe_group = OptionGroup(parser, "Options for named pipe Server")
    pipe_group.add_option("-i", "--input", type="string", dest="pipe_name", help="Filename of the named pipe")

    parser.add_option_group(pipe_group)
    
    (options, args) = parser.parse_args()

    if (options.xml and options.pipe) or (options.xml==None and options.pipe==None):
        parser.print_help()
        parser.error("You need to provide one of the following options, --xmlrpc or --npipe")

    if not options.output:
        parser.print_help()
        parser.error("You need to provide following options, --out=OutputDB.db")

    if options.pipe and not options.pipe_name:
        parser.print_help()
        parser.error("You need to provide following options, --input=named_pipe")
        
    return options
Пример #20
0
def build_script():
    usage = """
    usage: %prog [options] module_name
    """
    parser = OptionParser(usage = usage)
    translator.add_compile_options(parser)
    # override the default because we want print
    parser.set_defaults(print_statements=True)
    linker.add_linker_options(parser)
    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")

    top_module = args[0]
    for d in options.library_dirs:
        pyjs.path.append(os.path.abspath(d))

    translator_arguments=dict(
        debug=options.debug,
        print_statements = options.print_statements,
        function_argument_checking=options.function_argument_checking,
        attribute_checking=options.attribute_checking,
        source_tracking=options.source_tracking,
        line_tracking=options.line_tracking,
        store_source=options.store_source
        )

    l = SpidermonkeyLinker(top_module,
                           output=options.output,
                           platforms=[PLATFORM],
                           path=pyjs.path,
                           translator_arguments=translator_arguments)
    l()
Пример #21
0
def main():
    parser = OptionParser()
    parser.set_defaults(np=1)
    parser.add_option("--np", type=int, help="Number of Processors.")
    parser.add_option("--golden", help="Directory where golden files are stored.")
    parser.add_option("--outdir", help="Output directory.")
    parser.add_option("--nsweep", type=int, help="number of sweep")
    parser.add_option("--mesh", help="fluent case file")
    (options, args) = parser.parse_args()

    # convert path to absolute because we may cd to the test directory
    options.outdir   = os.path.abspath(options.outdir)
    options.golden   = os.path.abspath(os.path.join(options.golden,'GOLDEN'))
    options.mesh   = os.path.abspath(options.mesh)
    script = os.path.abspath('./FVMParticleMarking.py')

    if options.outdir:
        if not os.path.isdir(options.outdir):
            try:
                os.makedirs(options.outdir)
            except:
                print "error creating directory " + options.outdir
                sys.exit(1)
        os.chdir(options.outdir)

    mpi = 'mpirun -np %s %s %s %s' % (options.np, script, options.mesh, options.nsweep)    
    if os.system( mpi ):
        cleanup(-1)
    
    # OK.  Now check results.
    err = check_particles( options )
    cleanup(err)
Пример #22
0
def get_options():
    """
    Parse the arguments
    """
    # Instance the parser and define the usage message
    optparser = OptionParser(usage="""
    %prog [-vqld]""", version="%prog .1")

    # Define the options and the actions of each one
    optparser.add_option("-v", "--verbose", action="count", dest="verbose",
        help="Increment verbosity")
    optparser.add_option("-q", "--quiet", action="count", dest="quiet",
        help="Decrement verbosity")
    optparser.add_option("-l", "--log", help=("Uses the given log file "
        "inteast of the default"), action="store", dest="logfile")
    optparser.add_option("-i", "--insecure", help=("Will raise exceptions."),
        action="store_true", dest="insecure")
    optparser.add_option("-d", "--dummy", help=("Will execute a dummy test."),
        action="store_true", dest="dummy")

    # Define the default options
    optparser.set_defaults(verbose=0, quiet=0, logfile=LOG_FILE,
        conffile="", dummy=False, insecure=False)

    # Process the options
    options, args = optparser.parse_args()
    return options, args
Пример #23
0
def get_options():
    """
    Parse the arguments
    """
    # Instance the parser and define the usage message
    optparser = OptionParser(usage="""
    %prog [-vqdsc]""", version="%prog .2")

    # Define the options and the actions of each one
    optparser.add_option("-s", "--section", help=("Process only the given "
        "section"), action="store", dest="section")
    optparser.add_option("-c", "--config", help=("Uses the given conf file "
        "inteast of the default"), action="store", dest="conffile")
    optparser.add_option("-l", "--log", help=("Uses the given log file "
        "inteast of the default"), action="store", dest="logfile")
    optparser.add_option("-v", "--verbose", action="count", dest="verbose",
        help="Increment verbosity")
    optparser.add_option("-q", "--quiet", action="count", dest="quiet",
        help="Decrement verbosity")

    # Define the default options
    optparser.set_defaults(verbose=0, quiet=0, logfile=LOG_FILE,
        conffile="")

    # Process the options
    options, args = optparser.parse_args()
    return options, args
Пример #24
0
def parse_options():
    parser = OptionParser(usage="""%prog [options] server TASKFILE
or
%prog [options] client (TASKFILE | SERVER_ADDRESS)""")
    parser.set_defaults(type="simple", verbose=False)
    parser.add_option("-t", "--type", help="IPC type (-t help for more info)")
    parser.add_option("-p", "--port", help="port to use", type="int")
    parser.add_option("-v", "--verbose", help="print more detailed messages",
                      action="store_true")
    options, args = parser.parse_args()
    if options.type.lower() == "help" \
            or options.type.lower() not in IPC_HANDLERS.keys():
        parser.error("Supported IPC types: " + ", ".join(IPC_HANDLERS.keys()))
    if len(args) > 2:
        parser.error('invalid number of arguments')
    args[0] = args[0].lower()
    if args[0] not in ('client', 'server'):
        parser.error('argument must be either "server" or "client"')
    else:
        mode = args[0]
    taskfile = args[1]
    extraoptions = {}
    if options.port:
        extraoptions["port"] = options.port
    return (mode, taskfile, options.type.lower(), options.verbose,
            extraoptions)
def main (args):
	# Parse arguments
	parser = OptionParser(usage = "%prog [options]...",
		description = "Generate FallbackThaiUnicodeLinebreaker data "
			"tables from Thai wrap UserJS")
	parser.add_option("-i", "--input", dest = "infile",
		help = "location of Thai wrap UserJS", metavar = "FILE")
	parser.add_option("-o", "--output", dest = "outfile",
		help = "where to put generated tables file", metavar = "FILE")
	parser.set_defaults(infile = Default_infile, outfile = Default_outfile)
	(options, args) = parser.parse_args(args)
	assert len(args) == 1 # There should be no more arguments

	if options.infile == "-":
		f = sys.stdin
	else:
		f = open(options.infile)
	p = parse_userjs(f)
	f.close()

	if options.outfile == "-":
		f = sys.stdout
	else:
		f = open(options.outfile, "w")
	write_cpp_header(f, os.path.basename(options.outfile))
	write_cpp_word_list(f, cppify_name("Wordlist"), p["Wordlist"])
	for char_list in ("LeadingChars", "FollowingChars", "EOWChars"):
		write_cpp_char_list(f, cppify_name(char_list), p[char_list])
	write_cpp_footer(f, os.path.basename(options.outfile))
	f.close()

	return 0
Пример #26
0
def main():
    parser = OptionParser()
    parser.add_option('-c', '--config', dest='config',
                      help='path to configuration', metavar='FILE')
    parser.add_option('-v', '--verbose',
                      action='store_true', dest='verbose', default=False,
                      help='print status messages to stdout')
    parser.add_option('-u', '--user', dest='user',
                      help='user owning database', metavar='USER')
    parser.add_option('-d', '--database', dest='database',
                      help='database to back up', metavar='DB')
    parser.add_option('--daily', dest='type',
                      action='store_const', const='daily')
    parser.add_option('--local', dest='type',
                      action='store_const', const='')
    parser.set_defaults(type='daily')
    (options, args) = parser.parse_args()

    # Uncomment this to make -v actually work
    logger.setLevel(logging.INFO if options.verbose else
                    logging.WARNING)

    logger.debug(options)

    if options.config is None:
        die('No configuration file specified')
    load_config(options.config)

    logger.debug(config)

    result_file = get_backup_file_path(database=options.database, user=options.user, backup_type=options.type)
    logger.info('Backing up to "%s"' % (result_file,))
    perform_backup(result_file, database=options.database)

    remove_old_backups(result_file)
Пример #27
0
def main():
	parser = OptionParser( version="%prog 1.0", usage='Usage: %prog [options]' )

	parser.set_defaults( **{
		'verbose': False,
	} )

	parser.add_option( '-v', '--verbose', action='store_true' )

	opts, args = parser.parse_args()

	pat_dot = re.compile( r'\s+\.', re.UNICODE )

	for fn in os.listdir( '.' ):

		tags, rest = path.extract_tags( fn )

		dst = pat_dot.sub( '.', ' '.join( rest ) )

		p = ''.join( map( lambda x: '[' + x + ']', tags ) )

		dst = p and p + ' ' + dst or dst

		if os.path.exists( dst ):
			print( "Existed, skiped:", dst )
		else:
			try:
				os.renames( fn , dst )
			except OSError:
				print( "Failed:", dst )
Пример #28
0
    def commandline_options(self):
        """Set up the command line options."""
        parser = OptionParser(version="%prog " + VERSION,
            description="GUI front-end to compress png and jpg images via "
                "optipng, advpng and jpegoptim")

        parser.set_defaults(verbose=True)
        parser.add_option("-v", "--verbose", action="store_true",
            dest="verbose", help="Verbose mode (default)")
        parser.add_option("-q", "--quiet", action="store_false",
            dest="verbose", help="Quiet mode")

        parser.add_option("-f", "--file", action="store", type="string",
            dest="filename", help="compresses image and exit")
        parser.add_option("-d", "--directory", action="store", type="string",
            dest="directory", help="compresses images in directory and exit")

        options, args = parser.parse_args()

        # make sure we quit after processing finished if using cli
        if options.filename or options.directory:
            QObject.connect(self.thread, SIGNAL("finished()"), quit)

        # send to correct function
        if options.filename:
            self.file_from_cmd(options.filename.decode("utf-8"))
        if options.directory:
            self.dir_from_cmd(options.directory.decode("utf-8"))

        self.verbose = options.verbose
Пример #29
0
def run( arguments ):
    '''run( arguments )

    Parses and executes the given command-line `arguments`.

    Parameters:
    - arguments     A list of strings representing the command-line arguments
                    to ``restblog <command>``, e.g. ``sys.argv[2:]``
    '''

    # Parse

    usage = USAGE.strip()
    parser = OptionParser( usage=usage )
    options = dict(
        interactive=False,
    )
    parser.set_defaults( **options )
    parser.add_option( '-i', '--interactive', action='store_true', help='Prompt for missing credentials when connecting to the server.' )
    options, arguments = parser.parse_args( arguments )

    # Validate

    if not arguments:
        raise RuntimeError, 'Required arguments are missing.'
    count = len( arguments )
    if count != 1:
        raise RuntimeError, 'Unexpected arguments: %s' % ' '.join( arguments )

    # Execute

    file_name = arguments[0]
    insert( file_name, options.interactive )
Пример #30
0
def getOptions():
	""" Parse arguments and options. """
	usage = "Usage: %prog [options] <sacfile(s)>"
	parser = OptionParser(usage=usage)

	ofilename = 'sac.pkl'
	delta = -1
	parser.set_defaults(delta=delta)
	parser.set_defaults(ofilename=ofilename)
	parser.add_option('-s', '--s2p', action="store_true", dest='s2p',
		help='Convert SAC files to pickle file. Default is True.')
	parser.add_option('-p', '--p2s', action="store_true", dest='p2s',
		help='Convert pickle file (save headers) to SAC files.')
	parser.add_option('-d', '--delta',  dest='delta', type='float',
		help='Time sampling interval. Default is %f ' % delta)
	parser.add_option('-o', '--ofilename',  dest='ofilename', type='str',
		help='Output filename which works only with -s option.')
	parser.add_option('-z', '--zipmode',  dest='zipmode', type='str',
		help='Zip mode: bz2 or gz. Default is None.')

	opts, files = parser.parse_args(sys.argv[1:])
	opts.s2p = True
	if opts.p2s:
		opts.s2p = False
	if len(files) == 0:
		print parser.usage
		sys.exit()
	return opts, files