Budou main method for the command line tool.
507663
def main():
  
  args = docopt(__doc__)
  if args['--version']:
    print(__version__)
    sys.exit()

  result = parse(
      args['<source>'],
      segmenter=args['--segmenter'],
      language=args['--language'],
      classname=args['--classname'])
  print(result['html_code'])
  sys.exit()
168522
def main(args=None):
    
    api.config.init()
    zxbpp.init()
    zxbparser.init()
    arch.zx48k.backend.init()
    arch.zx48k.Translator.reset()
    asmparse.init()

    # ------------------------------------------------------------
    # Command line parsing
    # ------------------------------------------------------------
    parser = argparse.ArgumentParser(prog='zxb')
    parser.add_argument('PROGRAM', type=str,
                        help='BASIC program file')
    parser.add_argument('-d', '--debug', dest='debug', default=OPTIONS.Debug.value, action='count',
                        help='Enable verbosity/debugging output. Additional -d increase verbosity/debug level')
    parser.add_argument('-O', '--optimize', type=int, default=OPTIONS.optimization.value,
                        help='Sets optimization level. '
                             '0 = None (default level is {0})'.format(OPTIONS.optimization.value))
    parser.add_argument('-o', '--output', type=str, dest='output_file', default=None,
                        help='Sets output file. Default is input filename with .bin extension')
    parser.add_argument('-T', '--tzx', action='store_true',
                        help="Sets output format to tzx (default is .bin)")
    parser.add_argument('-t', '--tap', action='store_true',
                        help="Sets output format to tap (default is .bin)")
    parser.add_argument('-B', '--BASIC', action='store_true', dest='basic',
                        help="Creates a BASIC loader which loads the rest of the CODE. Requires -T ot -t")
    parser.add_argument('-a', '--autorun', action='store_true',
                        help="Sets the program to be run once loaded")
    parser.add_argument('-A', '--asm', action='store_true',
                        help="Sets output format to asm")
    parser.add_argument('-S', '--org', type=str, default=str(OPTIONS.org.value),
                        help="Start of machine code. By default %i" % OPTIONS.org.value)
    parser.add_argument('-e', '--errmsg', type=str, dest='stderr', default=OPTIONS.StdErrFileName.value,
                        help='Error messages file (standard error console by default)')
    parser.add_argument('--array-base', type=int, default=OPTIONS.array_base.value,
                        help='Default lower index for arrays ({0} by default)'.format(OPTIONS.array_base.value))
    parser.add_argument('--string-base', type=int, default=OPTIONS.string_base.value,
                        help='Default lower index for strings ({0} by default)'.format(OPTIONS.array_base.value))
    parser.add_argument('-Z', '--sinclair', action='store_true',
                        help='Enable by default some more original ZX Spectrum Sinclair BASIC features: ATTR, SCREEN$, '
                             'POINT')
    parser.add_argument('-H', '--heap-size', type=int, default=OPTIONS.heap_size.value,
                        help='Sets heap size in bytes (default {0} bytes)'.format(OPTIONS.heap_size.value))
    parser.add_argument('--debug-memory', action='store_true',
                        help='Enables out-of-memory debug')
    parser.add_argument('--debug-array', action='store_true',
                        help='Enables array boundary checking')
    parser.add_argument('--strict-bool', action='store_true',
                        help='Enforce boolean values to be 0 or 1')
    parser.add_argument('--enable-break', action='store_true',
                        help='Enables program execution BREAK detection')
    parser.add_argument('-E', '--emit-backend', action='store_true',
                        help='Emits backend code instead of ASM or binary')
    parser.add_argument('--explicit', action='store_true',
                        help='Requires all variables and functions to be declared before used')
    parser.add_argument('-D', '--define', type=str, dest='defines', action='append',
                        help='Defines de given macro. Eg. -D MYDEBUG or -D NAME=Value')
    parser.add_argument('-M', '--mmap', type=str, dest='memory_map', default=None,
                        help='Generate label memory map')
    parser.add_argument('-i', '--ignore-case', action='store_true',
                        help='Ignore case. Makes variable names are case insensitive')
    parser.add_argument('-I', '--include-path', type=str, default='',
                        help='Add colon separated list of directories to add to include path. e.g. -I dir1:dir2')
    parser.add_argument('--strict', action='store_true',
                        help='Enables strict mode. Force explicit type declaration')
    parser.add_argument('--headerless', action='store_true',
                        help='Header-less mode: omit asm prologue and epilogue')
    parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(VERSION))
    parser.add_argument('--parse-only', action='store_true',
                        help='Only parses to check for syntax and semantic errors')
    parser.add_argument('--append-binary', default=[], action='append',
                        help='Appends binary to tape file (only works with -t or -T)')
    parser.add_argument('--append-headless-binary', default=[], action='append',
                        help='Appends binary to tape file (only works with -t or -T)')

    options = parser.parse_args(args=args)

    # ------------------------------------------------------------
    # Setting of internal parameters according to command line
    # ------------------------------------------------------------

    OPTIONS.Debug.value = options.debug
    OPTIONS.optimization.value = options.optimize
    OPTIONS.outputFileName.value = options.output_file
    OPTIONS.StdErrFileName.value = options.stderr
    OPTIONS.array_base.value = options.array_base
    OPTIONS.string_base.value = options.string_base
    OPTIONS.Sinclair.value = options.sinclair
    OPTIONS.heap_size.value = options.heap_size
    OPTIONS.memoryCheck.value = options.debug_memory
    OPTIONS.strictBool.value = options.strict_bool or OPTIONS.Sinclair.value
    OPTIONS.arrayCheck.value = options.debug_array
    OPTIONS.emitBackend.value = options.emit_backend
    OPTIONS.enableBreak.value = options.enable_break
    OPTIONS.explicit.value = options.explicit
    OPTIONS.memory_map.value = options.memory_map
    OPTIONS.strict.value = options.strict
    OPTIONS.headerless.value = options.headerless

    OPTIONS.org.value = api.utils.parse_int(options.org)
    if OPTIONS.org.value is None:
        parser.error("Invalid --org option '{}'".format(options.org))

    if options.defines:
        for i in options.defines:
            name, val = tuple(i.split('=', 1))
            OPTIONS.__DEFINES.value[name] = val
            zxbpp.ID_TABLE.define(name, lineno=0)

    if OPTIONS.Sinclair.value:
        OPTIONS.array_base.value = 1
        OPTIONS.string_base.value = 1
        OPTIONS.strictBool.value = True
        OPTIONS.case_insensitive.value = True

    if options.ignore_case:
        OPTIONS.case_insensitive.value = True

    debug.ENABLED = OPTIONS.Debug.value

    if int(options.tzx) + int(options.tap) + int(options.asm) + int(options.emit_backend) + \
            int(options.parse_only) > 1:
        parser.error("Options --tap, --tzx, --emit-backend, --parse-only and --asm are mutually exclusive")
        return 3

    if options.basic and not options.tzx and not options.tap:
        parser.error('Option --BASIC and --autorun requires --tzx or tap format')
        return 4

    if options.append_binary and not options.tzx and not options.tap:
        parser.error('Option --append-binary needs either --tap or --tzx')
        return 5

    OPTIONS.use_loader.value = options.basic
    OPTIONS.autorun.value = options.autorun

    if options.tzx:
        OPTIONS.output_file_type.value = 'tzx'
    elif options.tap:
        OPTIONS.output_file_type.value = 'tap'
    elif options.asm:
        OPTIONS.output_file_type.value = 'asm'
    elif options.emit_backend:
        OPTIONS.output_file_type.value = 'ic'

    args = [options.PROGRAM]
    if not os.path.exists(options.PROGRAM):
        parser.error("No such file or directory: '%s'" % args[0])
        return 2

    if OPTIONS.memoryCheck.value:
        OPTIONS.__DEFINES.value['__MEMORY_CHECK__'] = ''
        zxbpp.ID_TABLE.define('__MEMORY_CHECK__', lineno=0)

    if OPTIONS.arrayCheck.value:
        OPTIONS.__DEFINES.value['__CHECK_ARRAY_BOUNDARY__'] = ''
        zxbpp.ID_TABLE.define('__CHECK_ARRAY_BOUNDARY__', lineno=0)

    OPTIONS.include_path.value = options.include_path
    OPTIONS.inputFileName.value = zxbparser.FILENAME = \
        os.path.basename(args[0])

    if not OPTIONS.outputFileName.value:
        OPTIONS.outputFileName.value = \
            os.path.splitext(os.path.basename(OPTIONS.inputFileName.value))[0] + os.path.extsep + \
            OPTIONS.output_file_type.value

    if OPTIONS.StdErrFileName.value:
        OPTIONS.stderr.value = open_file(OPTIONS.StdErrFileName.value, 'wt', 'utf-8')

    zxbpp.setMode('basic')
    zxbpp.main(args)

    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    input_ = zxbpp.OUTPUT
    zxbparser.parser.parse(input_, lexer=zxblex.lexer, tracking=True,
                           debug=(OPTIONS.Debug.value > 2))
    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    # Optimizations
    optimizer = api.optimize.OptimizerVisitor()
    optimizer.visit(zxbparser.ast)

    # Emits intermediate code
    translator = arch.zx48k.Translator()
    translator.visit(zxbparser.ast)

    if gl.DATA_IS_USED:
        gl.FUNCTIONS.extend(gl.DATA_FUNCTIONS)

    # This will fill MEMORY with pending functions
    func_visitor = arch.zx48k.FunctionTranslator(gl.FUNCTIONS)
    func_visitor.start()

    # Emits data lines
    translator.emit_data_blocks()
    # Emits default constant strings
    translator.emit_strings()
    # Emits jump tables
    translator.emit_jump_tables()

    if OPTIONS.emitBackend.value:
        with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file:
            for quad in translator.dumpMemory(backend.MEMORY):
                output_file.write(str(quad) + '\n')

            backend.MEMORY[:] = []  # Empties memory
            # This will fill MEMORY with global declared variables
            translator = arch.zx48k.VarTranslator()
            translator.visit(zxbparser.data_ast)

            for quad in translator.dumpMemory(backend.MEMORY):
                output_file.write(str(quad) + '\n')
        return 0  # Exit success

    # Join all lines into a single string and ensures an INTRO at end of file
    asm_output = backend.emit(backend.MEMORY)
    asm_output = optimize(asm_output) + '\n'

    asm_output = asm_output.split('\n')
    for i in range(len(asm_output)):
        tmp = backend.ASMS.get(asm_output[i], None)
        if tmp is not None:
            asm_output[i] = '\n'.join(tmp)

    asm_output = '\n'.join(asm_output)

    # Now filter them against the preprocessor again
    zxbpp.setMode('asm')
    zxbpp.OUTPUT = ''
    zxbpp.filter_(asm_output, args[0])

    # Now output the result
    asm_output = zxbpp.OUTPUT.split('\n')
    get_inits(asm_output)  # Find out remaining inits
    backend.MEMORY[:] = []

    # This will fill MEMORY with global declared variables
    translator = arch.zx48k.VarTranslator()
    translator.visit(zxbparser.data_ast)
    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    tmp = [x for x in backend.emit(backend.MEMORY) if x.strip()[0] != '#']
    asm_output += tmp
    asm_output = backend.emit_start() + asm_output
    asm_output += backend.emit_end(asm_output)

    if options.asm:  # Only output assembler file
        with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file:
            output(asm_output, output_file)
    elif not options.parse_only:
        fout = StringIO()
        output(asm_output, fout)
        asmparse.assemble(fout.getvalue())
        fout.close()
        asmparse.generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type.value,
                                 binary_files=options.append_binary,
                                 headless_binary_files=options.append_headless_binary)
        if gl.has_errors:
            return 5  # Error in assembly

    if OPTIONS.memory_map.value:
        with open_file(OPTIONS.memory_map.value, 'wt', 'utf-8') as f:
            f.write(asmparse.MEMORY.memory_map)

    return gl.has_errors
448353
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    from fundamentals.mysql import sqlite2mysql
    converter = sqlite2mysql(
        log=log,
        settings=settings,
        pathToSqlite=pathToSqliteDB,
        tablePrefix=tablePrefix,
        dbConn=dbConn
    )
    converter.convert_sqlite_to_mysql()

    return
1010097
def main():
    
    arguments = docopt(main.__doc__)

    if arguments.get('--version'):
        print('with {}'.format(withtool.__version__))
        sys.exit()

    while True:
        sub = yield from get_prompt(arguments['<command>'])
        call = '{cmd} {sub}'.format(cmd=arguments['<command>'], sub=sub)
        run(call)
529143
def main():
    """"""
    parser = get_parser()
    args = parser.parse_args()
    if hasattr(args, 'func') and args.func:
        args.func(args)
    else:
        parser.print_help()
9317
def main(argv=None):
    '''  '''
    parser = get_parser()

    # Parse arguments and run the function
    global args
    args = parser.parse_args(argv)
    args.func()
603255
def main():
    """"""
    actions = []
    try:
        # Parse the command line arguments.
        options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
            'convert', 'to-html', 'demo', 'help',
        ])
        # Map command line options to actions.
        for option, value in options:
            if option in ('-c', '--convert', '--to-html'):
                actions.append(functools.partial(convert_command_output, *arguments))
                arguments = []
            elif option in ('-d', '--demo'):
                actions.append(demonstrate_colored_logging)
            elif option in ('-h', '--help'):
                usage(__doc__)
                return
            else:
                assert False, "Programming error: Unhandled option!"
        if not actions:
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    for function in actions:
        function()
87170
def main():  # pragma: no cover
    """"""
    entry_point.add_command(CLI.version)
    entry_point.add_command(UserCLI.user)
    entry_point.add_command(GroupCLI.group)
    entry_point.add_command(AuditCLI.audit)
    entry_point.add_command(KeyCLI.key)

    entry_point()
618883
def main(self, argv=None, exit=True):
        
        return CommandRecipe(self).main(argv, exit)
484543
def main():
    
    parser = argparse.ArgumentParser(description='Longclaw CLI')
    subparsers = parser.add_subparsers()
    start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project')
    start.add_argument('project_name', help='Name of the project')
    start.set_defaults(func=create_project)

    build = subparsers.add_parser('build', help='Build the front-end assets for Longclaw')
    build.set_defaults(func=build_assets)

    args = parser.parse_args()

    # Python 3 lost the default behaviour to fall back to printing
    # help if a subparser is not selected.
    # See: https://bugs.python.org/issue16308
    # So we must explicitly catch the error thrown on py3 if
    # no commands given to longclaw
    try:
        args.func(args)
    except AttributeError:
        parser.print_help()
        sys.exit(0)
993176
def main(args=sys.argv):
    """"""
    # Don't make changes to sys.argv
    args = list(args)

    # Remove arg[0]
    args.pop(0)

    # Pop off the options
    clear_opt = False
    if '-c' in args:
        args.remove('-c')
        clear_opt = True
    elif '--clear' in args:
        args.remove('--clear')
        clear_opt = True

    if len(args) == 0:
        cfg_path = os.path.expanduser('~/.wallsrc')
    elif len(args) == 1:
        cfg_path = args[0]
    else:
        stderr_and_exit('Usage: walls [-c] [config_file]\n')

    config = load_config(cfg_path)

    run(config, clear_opt)
303256
def main():
    """"""
    # Initialize logging to the terminal.
    coloredlogs.install()
    # Prepare for command line argument parsing.
    action = show_matching_entry
    program_opts = dict(exclude_list=[])
    show_opts = dict(filters=[], use_clipboard=is_clipboard_supported())
    verbosity = 0
    # Parse the command line arguments.
    try:
        options, arguments = getopt.gnu_getopt(
            sys.argv[1:],
            "elnp:f:x:vqh",
            ["edit", "list", "no-clipboard", "password-store=", "filter=", "exclude=", "verbose", "quiet", "help"],
        )
        for option, value in options:
            if option in ("-e", "--edit"):
                action = edit_matching_entry
            elif option in ("-l", "--list"):
                action = list_matching_entries
            elif option in ("-n", "--no-clipboard"):
                show_opts["use_clipboard"] = False
            elif option in ("-p", "--password-store"):
                stores = program_opts.setdefault("stores", [])
                stores.append(PasswordStore(directory=value))
            elif option in ("-f", "--filter"):
                show_opts["filters"].append(value)
            elif option in ("-x", "--exclude"):
                program_opts["exclude_list"].append(value)
            elif option in ("-v", "--verbose"):
                coloredlogs.increase_verbosity()
                verbosity += 1
            elif option in ("-q", "--quiet"):
                coloredlogs.decrease_verbosity()
                verbosity -= 1
            elif option in ("-h", "--help"):
                usage(__doc__)
                return
            else:
                raise Exception("Unhandled option! (programming error)")
        if not (arguments or action == list_matching_entries):
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    # Execute the requested action.
    try:
        show_opts["quiet"] = verbosity < 0
        kw = show_opts if action == show_matching_entry else {}
        action(QuickPass(**program_opts), arguments, **kw)
    except PasswordStoreError as e:
        # Known issues don't get a traceback.
        logger.error("%s", e)
        sys.exit(1)
    except KeyboardInterrupt:
        # If the user interrupted an interactive prompt they most likely did so
        # intentionally, so there's no point in generating more output here.
        sys.exit(1)
223080
def main():
    """"""
    parser = get_args_parser()
    args = parser.parse_args()
    config = Config.from_parse_args(args)
    migrate(config)
1268634
def main():
    """"""

    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--outfile', metavar='output_file_path',
                        help="Save calltree stats to <outfile>")
    parser.add_argument('-i', '--infile', metavar='input_file_path',
                        help="Read Python stats from <infile>")
    parser.add_argument('-k', '--kcachegrind',
                        help="Run the kcachegrind tool on the converted data",
                        action="store_true")
    parser.add_argument('-r', '--run-script',
                        nargs=argparse.REMAINDER,
                        metavar=('scriptfile', 'args'),
                        dest='script',
                        help="Name of the Python script to run to collect"
                        " profiling data")
    args = parser.parse_args()

    outfile = args.outfile

    if args.script is not None:
        # collect profiling data by running the given script
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.script[0])

        fd, tmp_path = tempfile.mkstemp(suffix='.prof', prefix='pyprof2calltree')
        os.close(fd)
        try:
            cmd = [
                sys.executable,
                '-m', 'cProfile',
                '-o', tmp_path,
            ]
            cmd.extend(args.script)
            subprocess.check_call(cmd)

            kg = CalltreeConverter(tmp_path)
        finally:
            os.remove(tmp_path)

    elif args.infile is not None:
        # use the profiling data from some input file
        if not args.outfile:
            outfile = '%s.log' % os.path.basename(args.infile)

        if args.infile == outfile:
            # prevent name collisions by appending another extension
            outfile += ".log"

        kg = CalltreeConverter(pstats.Stats(args.infile))

    else:
        # at least an input file or a script to run is required
        parser.print_usage()
        sys.exit(2)

    if args.outfile is not None or not args.kcachegrind:
        # user either explicitly required output file or requested by not
        # explicitly asking to launch kcachegrind
        sys.stderr.write("writing converted data to: %s\n" % outfile)
        with open(outfile, 'w') as f:
            kg.output(f)

    if args.kcachegrind:
        sys.stderr.write("launching kcachegrind\n")
        kg.visualize()
1070249
def main(cls, args=None):
        
        organizer = cls()
        organizer.parse_args(args)
        if not organizer.no_modification:
            organizer.config.save()
690868
def main():
    """"""
    parser = build_command_parser()
    options = parser.parse_args()
    file_pointer = options.filename
    input_format = options.input_format

    with file_pointer:
        json_data = json.load(file_pointer)

    if input_format == SIMPLE_JSON:
        report = Report(json_data)
    elif input_format == EXTENDED_JSON:
        report = Report(
            json_data.get('messages'),
            json_data.get('stats'),
            json_data.get('previous'))

    print(report.render(), file=options.output)
720529
def main():
    """"""
    logging.basicConfig(format=LOGGING_FORMAT)

    parser = argparse.ArgumentParser(description=main.__doc__)
    add_debug(parser)
    add_app(parser)
    add_env(parser)
    add_region(parser)
    args = parser.parse_args()

    logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)

    assert destroy_elb(**vars(args))