Command line interface.

    :param list args: command line options (defaults to sys.argv)
    :returns: exit code
    :rtype: int
349585
def main(args=None):
    
    parser = ArgumentParser(
        prog='baseline',
        description=DESCRIPTION)

    parser.add_argument(
        'path', nargs='*',
        help='module or directory path')

    parser.add_argument(
        '--movepath', help='location to move script updates')

    parser.add_argument(
        '-w', '--walk', action='store_true',
        help='recursively walk directories')

    args = parser.parse_args(args)

    paths = args.path or ['.']

    paths = [path for pattern in paths for path in glob(pattern)]

    if args.walk:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            for root, _dirs, files in os.walk(dirpath):
                paths += (os.path.join(root, filename) for filename in files)
    else:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            paths += (os.path.join(dirpath, pth) for pth in os.listdir(dirpath))

    update_paths = [
        os.path.relpath(p) for p in paths if p.lower().endswith(UPDATE_EXT)]

    exitcode = 0

    if update_paths:
        script_paths = [pth[:-len(UPDATE_EXT)] + '.py' for pth in update_paths]

        print('Found updates for:')
        for path in script_paths:
            print('  ' + path)
        print()

        if not args.movepath:
            try:
                input('Hit [ENTER] to update, [Ctrl-C] to cancel ')
            except KeyboardInterrupt:
                print()
                print('Update canceled.')
                exitcode = 1
            else:
                print()

        if exitcode == 0:
            for script_path, update_path in zip(script_paths, update_paths):
                if args.movepath:
                    script_path = os.path.join(args.movepath, script_path)
                    if update_path.startswith('..'):
                        raise RuntimeError(
                            'destination outside of move path: ' + script_path)
                    script_dirpath = os.path.dirname(script_path)
                    if not os.path.isdir(script_dirpath):
                        os.makedirs(script_dirpath)
                with open(update_path) as update:
                    new_content = update.read()
                with open(script_path, 'w') as script:
                    script.write(new_content)
                os.remove(update_path)
                print(update_path + ' -> ' + script_path)

    return exitcode
580457
def process(self, argument_list):
        
        arg_index = 0
        for a in argument_list:
            opt_and_val = a.split("=", 1)
            opt_name = opt_and_val[0]
            try:
                # option
                argument = self.options[opt_name]
            except KeyError:
                # argument
                try:
                    argument = self.arguments[arg_index]
                except IndexError:
                    logger.error("option/argument %r not specified", a)
                    raise NoSuchOptionOrArgument("No such option or argument: %r" % opt_name)
            logger.info("argument found: %s", argument)

            safe_arg_name = normalize_arg_name(argument.name)  # so we can access names-with-dashes

            logger.info("argument is available under name %r", safe_arg_name)

            if isinstance(argument, Argument):
                arg_index += 1
                value = (a, )
            else:
                try:
                    value = (opt_and_val[1], )
                except IndexError:
                    value = tuple()

            arg_val = argument.action(*value)

            logger.info("argument %r has value %r", safe_arg_name, arg_val)
            self.given_arguments[safe_arg_name] = arg_val
        return self.given_arguments
422747
def main(argv=None):
    # type: (Union[NoneType, List[str]]) -> NoneType
    
    app = application.Application()
    app.run(argv)
    app.exit()
1291339
def run(self, args):
        
        # set output stream.
        if self.outputStream:
            self.linter.reporter.set_output(self.outputStream)
        try:
            args = self.linter.load_command_line_configuration(args)
        except SystemExit as exc:
            if exc.code == 2:  # bad options
                exc.code = 32
            raise
        if not args:
            self.displayHelp()
        # Check for 'strict-epydoc' option.
        if self.allowOptions and not self.linter.option_value("strict-epydoc"):
            for msg in ["W9203", "W9205"]:
                self.linter.disable(msg)

        # insert current working directory to the python path to have a correct
        # behaviour.
        sys.path.insert(0, os.getcwd())
        # set exceptions for name checking.
        self.setNameExceptions(args)

        # check for diff option.
        self.diffOption = self.linter.option_value("diff")
        if self.diffOption:
            self.prepareDiff()

        # check codes.
        self.linter.check(args)

        # show diff of warnings if diff option on.
        if self.diffOption:
            diffCount = self.showDiffResults()
            exitCode = 1 if diffCount else 0
            sys.exit(exitCode)

        sys.exit(self.linter.msg_status)
852149
def _get_win_argv():
    

    assert is_win

    argc = ctypes.c_int()
    try:
        argv = winapi.CommandLineToArgvW(
            winapi.GetCommandLineW(), ctypes.byref(argc))
    except WindowsError:
        return []

    if not argv:
        return []

    res = argv[max(0, argc.value - len(sys.argv)):argc.value]

    winapi.LocalFree(argv)

    return res
89491
def parse_command_line_parameters(argv=None):
    
    usage =\
        'usage: %prog [options] input_sequences_filepath'
    version = 'Version: %prog ' + __version__
    parser = OptionParser(usage=usage, version=version)

    parser.add_option('-o', '--output_fp', action='store',
                      type='string', dest='output_fp', help='Path to store ' +
                      'output file [default: generated from input_sequences_filepath]')

    parser.add_option('-c', '--min_confidence', action='store',
                      type='float', dest='min_confidence', help='minimum confidence ' +
                      'level to return a classification [default: %default]')

    parser.set_defaults(verbose=False, min_confidence=0.80)

    opts, args = parser.parse_args(argv)
    if len(args) != 1:
        parser.error('Exactly one argument is required.')

    return opts, args
1265178
def get_list(self, input_string):
        

        if input_string in ('--ensemble_list', '--fpf'):

            # was the flag set?
            try:
                index_low = self.args.index(input_string) + 1
            except ValueError:
                if input_string in self.required:
                    print("\n {flag} is required".format(flag=input_string))
                    print_short_help()
                    sys.exit(1)
                else:
                    return None

            # the flag was set, so check if a value was set, otherwise exit
            try:
                if self.args[index_low] in self.flags:
                    print("\n {flag} was set but a value was not specified".format(flag=input_string))
                    print_short_help()
                    sys.exit(1)
            except IndexError:
                print("\n {flag} was set but a value was not specified".format(input_string))
                print_short_help()
                sys.exit(1)

            # at least one value was set
            index_high = index_low
            try:
                # if the flag wasn't the last argument specified
                while self.args[index_high] not in self.flags:
                    index_high += 1
            except IndexError:
                # if it was, then handle it accordingly
                index_high = self.args.index(self.args[-1])
                return self.args[index_low:index_high + 1]
            # return a list of input files
            if index_low == index_high:
                inputList = []
                inputList.append(self.args[index_low])
                return inputList
            else:
                return self.args[index_low:index_high]
449096
def listify(*args):
    
    if (len(args) == 1) and callable(args[0]):
        func = args[0]

        @wraps(func)
        def _inner(*args, **kwargs):
            return list(func(*args, **kwargs))
        return _inner
    else:
        return list(args)
923139
def pl (listoflists):
    
    for row in listoflists:
        if row[-1] == '\n':
            print(row, end=' ')
        else:
            print(row)
    return None
1103249
def call(self, args, devnull=False):
        
        if self.debug:
            click.echo(subprocess.list2cmdline(args))
            click.confirm('Continue?', default=True, abort=True)
        try:
            kwargs = {}
            if devnull:
                # Pipe to /dev/null (or equivalent).
                kwargs['stderr'] = subprocess.STDOUT
                kwargs['stdout'] = self.FNULL
            ret_code = subprocess.call(args, **kwargs)
        except subprocess.CalledProcessError:
            return False
        return ret_code
853188
def command_line(argv):
    
    arguments = parse_command_line(argv)
    if arguments.generate:
        generate_fixer_file(arguments.generate)
    paths = edit_files(arguments.patterns,
                       expressions=arguments.expressions,
                       functions=arguments.functions,
                       executables=arguments.executables,
                       start_dirs=arguments.start_dirs,
                       max_depth=arguments.max_depth,
                       dry_run=arguments.dry_run,
                       output=arguments.output,
                       encoding=arguments.encoding,
                       newline=arguments.newline)
    # If the output is not sys.stdout, we need to close it because
    # argparse.FileType does not do it for us.
    is_sys = arguments.output in [sys.stdout, sys.stderr]
    if not is_sys and isinstance(arguments.output, io.IOBase):
        arguments.output.close()
    return paths
885358
def write_line_list(argname, cmd, basename, filename):
    

    values = getattr(cmd.distribution, argname, None)
    if isinstance(values, list):
        values = '\n'.join(values)
    cmd.write_or_delete_file(argname, filename, values, force=True)
708064
protected int list(String[] args) {
		// Parse command line options
		CommandLine line;
		try {
			line = parser.parse(LIST_OPTIONS, args, false);
		}
		catch (MissingOptionException e) {
			System.out.println(e.getMessage());
			printHelpForList();
			return 1;
		}
		catch (UnrecognizedOptionException e) {
			System.out.println(e.getMessage());
			printHelpForList();
			return 2;
		}
		catch (Exception e) {
			return handleError(e);
		}
		
		if (printHelp) {
			printHelpForList();
			return 0;
		}
		
		// get list options
		boolean running = line.hasOption(RUNNING_OPTION.getOpt());
		boolean scheduled = line.hasOption(SCHEDULED_OPTION.getOpt());
		
		if (!running && !scheduled) {
			System.out.println("Error: Specify the status of the jobs to list.");
			printHelpForList();
			return 1;
		}
		
		ExtendedManagementProtocol jmConn = null;
		try {
			jmConn = getJobManagerConnection(line);
			if (jmConn == null) {
				printHelpForList();
				return 1;
			}
			
			List<RecentJobEvent> recentJobs = jmConn.getRecentJobs();
			
			ArrayList<RecentJobEvent> runningJobs = null;
			ArrayList<RecentJobEvent> scheduledJobs = null;
			if (running) {
				runningJobs = new ArrayList<RecentJobEvent>();
			}
			if (scheduled) {
				scheduledJobs = new ArrayList<RecentJobEvent>();
			}
			
			for (RecentJobEvent rje : recentJobs) {
				
				if (running && rje.getJobStatus().equals(JobStatus.RUNNING)) {
					runningJobs.add(rje);
				}
				if (scheduled && rje.getJobStatus().equals(JobStatus.SCHEDULED)) {
					scheduledJobs.add(rje);
				}
			}
			
			SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
			Comparator<RecentJobEvent> njec = new Comparator<RecentJobEvent>(){
				
				@Override
				public int compare(RecentJobEvent o1, RecentJobEvent o2) {
					return (int)(o1.getTimestamp()-o2.getTimestamp());
				}
			};
			
			if (running) {
				if(runningJobs.size() == 0) {
					System.out.println("No running jobs.");
				} else {
					Collections.sort(runningJobs, njec);
					
					System.out.println("------------------------ Running Jobs ------------------------");
					for(RecentJobEvent je : runningJobs) {
						System.out.println(df.format(new Date(je.getTimestamp()))+" : "+je.getJobID().toString()+" : "+je.getJobName());
					}
					System.out.println("--------------------------------------------------------------");
				}
			}
			if (scheduled) {
				if(scheduledJobs.size() == 0) {
					System.out.println("No scheduled jobs.");
				} else {
					Collections.sort(scheduledJobs, njec);
					
					System.out.println("----------------------- Scheduled Jobs -----------------------");
					for(RecentJobEvent je : scheduledJobs) {
						System.out.println(df.format(new Date(je.getTimestamp()))+" : "+je.getJobID().toString()+" : "+je.getJobName());
					}
					System.out.println("--------------------------------------------------------------");
				}
			}
			return 0;
		}
		catch (Throwable t) {
			return handleError(t);
		}
		finally {
			if (jmConn != null) {
				try {
					RPC.stopProxy(jmConn);
				} catch (Throwable t) {
					System.out.println("Could not cleanly shut down connection from compiler to job manager");
				}
			}
			jmConn = null;
		}
		
	}
39951
def do_args(self, line):
        
        args = self.line_to_args(line)
        for idx in range(len(args)):
            self.print("arg[%d] = '%s'" % (idx, args[idx]))
115597
def command_line_interfaces(self):
        
        interfaces = []
        for _, module in self.modules.items():
            for entry in dir(module):
                if entry.endswith('CommandLine'):
                    interfaces.append((module, entry))
        return interfaces
196216
def run_cmd(cmd, show_output=True, raise_errs=True, **kwargs):
    
    internal_assert(cmd and isinstance(cmd, list), "console commands must be passed as non-empty lists")
    try:
        from shutil import which
    except ImportError:
        pass
    else:
        cmd[0] = which(cmd[0]) or cmd[0]
    logger.log_cmd(cmd)
    try:
        if show_output and raise_errs:
            return subprocess.check_call(cmd, **kwargs)
        elif show_output:
            return subprocess.call(cmd, **kwargs)
        else:
            stdout, stderr, retcode = call_output(cmd, **kwargs)
            output = "".join(stdout + stderr)
            if retcode and raise_errs:
                raise subprocess.CalledProcessError(retcode, cmd, output=output)
            return output
    except OSError:
        logger.log_exc()
        if raise_errs:
            raise subprocess.CalledProcessError(oserror_retcode, cmd)
        elif show_output:
            return oserror_retcode
        else:
            return ""
942066
def run(self):
    
    self.parser = MultioptOptionParser(
      usage="%prog <command> [options] [args]",
      prog=self.clsname,
      version=self.version,
      option_list=self.global_options,
      description=self.desc_short,
      commands=self.command_set,
      epilog=self.footer
    )
    
    try:
      self.options, self.args = self.parser.parse_args(self.argv)    
    except Exception, e:
      print str(e)
      pass

    if len(self.args) < 1:
      self.parser.print_lax_help()
      return 2
    
    self.command = self.args.pop(0)
    showHelp = False
    
    if self.command == 'help': 
      if len(self.args) < 1:
        self.parser.print_lax_help()
        return 2
      else:
        self.command = self.args.pop()
        showHelp = True

    if self.command not in self.valid_commands:
      self.parser.print_cmd_error(self.command)
      return 2

    self.command_set[self.command].set_cmdname(self.command)
    subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options)
    subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args)

    if showHelp:
      subcmd_parser.print_help_long()
      return 1

    try:
      self.command_set[self.command].func(subcmd_options, *subcmd_args)
    except (CommandError, TypeError), e:
      # self.parser.print_exec_error(self.command, str(e))
      subcmd_parser.print_exec_error(self.command, str(e))
      print 
      # @TODO show command help
      # self.parser.print_lax_help()
      return 2

      
    return 1