Internal method to parse the tc_playbook_out_variable arg.

        **Example Variable Format**::

            #App:1234:status!String,#App:1234:status_code!String
190191
def _parse_out_variable(self):
        
        self._out_variables = {}
        self._out_variables_type = {}
        if self.tcex.default_args.tc_playbook_out_variables:
            variables = self.tcex.default_args.tc_playbook_out_variables.strip()
            for o in variables.split(','):
                # parse the variable to get individual parts
                parsed_key = self.parse_variable(o)
                variable_name = parsed_key['name']
                variable_type = parsed_key['type']
                # store the variables in dict by name (e.g. "status_code")
                self._out_variables[variable_name] = {'variable': o}
                # store the variables in dict by name-type (e.g. "status_code-String")
                vt_key = '{}-{}'.format(variable_name, variable_type)
                self._out_variables_type[vt_key] = {'variable': o}
75867
def parse_vars(self, args):
        
        result = {}
        for arg in args:
            if '=' not in arg:
                raise ValueError(
                    'Variable assignment %r invalid (no "=")'
                    % arg)
            name, value = arg.split('=', 1)
            result[name] = value
        return result
679220
def _parse_args(args: List[str]) -> _UpdateArgumentsRunConfig:
    
    parser = argparse.ArgumentParser(
        prog="gitlab-update-variables", description="Tool for setting a GitLab project's build variables")
    add_common_arguments(parser)
    parser.add_argument("config_location", type=str, help="Location of the configuration file")
    parser.add_argument("--setting-repository", dest="setting_repository", nargs="+", type=str,
                        help="Directory from which variable settings groups may be sourced")
    parser.add_argument("--default-setting-extension", dest="default_setting_extensions",nargs="+", type=str,
                        help="Extensions to try adding to the variable to source location if it does not exist")

    arguments = parser.parse_args(args)
    return _UpdateArgumentsRunConfig(
        arguments.config_location, arguments.setting_repository, arguments.default_setting_extensions,
        url=arguments.url, token=arguments.token, debug=arguments.debug)
1336759
static void processArgs(String[] args, final PrintStream out, final PrintStream err) {
        GroovyCommand groovyCommand = new GroovyCommand();
        CommandLine parser = new CommandLine(groovyCommand).setUnmatchedArgumentsAllowed(true).setStopAtUnmatched(true);
        try {
            List<CommandLine> result = parser.parse(args);
            if (CommandLine.printHelpIfRequested(result, out, err, Help.Ansi.AUTO)) {
                return;
            }
            // TODO: pass printstream(s) down through process
            if (!groovyCommand.process(parser)) {
                // If we fail, then exit with an error so scripting frameworks can catch it.
                System.exit(1);
            }

        } catch (ParameterException ex) { // command line arguments could not be parsed
            err.println(ex.getMessage());
            ex.getCommandLine().usage(err);
        } catch (IOException ioe) {
            err.println("error: " + ioe.getMessage());
        }
    }
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
1011510
def _load_playbook_from_file(self, path, vars={}):
        '''
        
        '''

        playbook_data  = utils.parse_yaml_from_file(path)
        accumulated_plays = []
        play_basedirs = []

        if type(playbook_data) != list:
            raise errors.AnsibleError("parse error: playbooks must be formatted as a YAML list")

        basedir = os.path.dirname(path) or '.'
        utils.plugins.push_basedir(basedir)
        for play in playbook_data:
            if type(play) != dict:
                raise errors.AnsibleError("parse error: each play in a playbook must a YAML dictionary (hash), recieved: %s" % play)
            if 'include' in play:
                tokens = shlex.split(play['include'])

                items = ['']
                for k in play.keys():
                    if not k.startswith("with_"):
                        # These are the keys allowed to be mixed with playbook includes
                        if k in ("include", "vars"):
                            continue
                        else:
                            raise errors.AnsibleError("parse error: playbook includes cannot be used with other directives: %s" % play)
                    plugin_name = k[5:]
                    if plugin_name not in utils.plugins.lookup_loader:
                        raise errors.AnsibleError("cannot find lookup plugin named %s for usage in with_%s" % (plugin_name, plugin_name))
                    terms = utils.template_ds(basedir, play[k], vars)
                    items = utils.plugins.lookup_loader.get(plugin_name, basedir=basedir, runner=None).run(terms, inject=vars)

                for item in items:
                    incvars = vars.copy()
                    incvars['item'] = item
                    if 'vars' in play:
                        if isinstance(play['vars'], dict):
                            incvars.update(play['vars'])
                        elif isinstance(play['vars'], list):
                            for v in play['vars']:
                                incvars.update(v)
                    for t in tokens[1:]:
                        (k,v) = t.split("=", 1)
                        incvars[k] = utils.template_ds(basedir, v, incvars)
                    included_path = utils.path_dwim(basedir, tokens[0])
                    (plays, basedirs) = self._load_playbook_from_file(included_path, incvars)
                    for p in plays:
                        if 'vars' not in p:
                            p['vars'] = {}
                        if isinstance(p['vars'], dict):
                            p['vars'].update(incvars)
                        elif isinstance(p['vars'], list):
                            p['vars'].extend([dict(k=v) for k,v in incvars.iteritems()])
                    accumulated_plays.extend(plays)
                    play_basedirs.extend(basedirs)
            else:
                accumulated_plays.append(play)
                play_basedirs.append(basedir)

        return (accumulated_plays, play_basedirs)
380767
def load_cli_args(self):
        
        parser = argparse.ArgumentParser(description='QTPyLib Reporting',
                                         formatter_class=argparse.ArgumentDefaultsHelpFormatter)

        parser.add_argument('--port', default=self.args["port"],
                            help='HTTP port to use', type=int)
        parser.add_argument('--host', default=self.args["host"],
                            help='Host to bind the http process to')
        parser.add_argument('--blotter',
                            help='Use this Blotter\'s MySQL server settings')
        parser.add_argument('--nopass',
                            help='Skip password for web app (flag)',
                            action='store_true')

        # only return non-default cmd line args
        # (meaning only those actually given)
        cmd_args, _ = parser.parse_known_args()
        args = {arg: val for arg, val in vars(
            cmd_args).items() if val != parser.get_default(arg)}
        return args
958464
def _get_command_args(self, command, args):
        ''''''
        command_args = {}
        command_argument_names =\
            command.__code__.co_varnames[:command.__code__.co_argcount]

        for varname in command_argument_names:
            if varname == 'args':
                command_args['args'] = args
            elif varname in self.provide_args:
                command_args[varname] = self.provide_args[varname]
            else:
                command_args[varname] = getattr(args, varname)
        return command_args
644754
def print_environment_vars(env):
    
    ansible_env = {k: v for (k, v) in env.items() if 'ANSIBLE_' in k}
    print_debug('ANSIBLE ENVIRONMENT', safe_dump(ansible_env))

    molecule_env = {k: v for (k, v) in env.items() if 'MOLECULE_' in k}
    print_debug('MOLECULE ENVIRONMENT', safe_dump(molecule_env))

    combined_env = ansible_env.copy()
    combined_env.update(molecule_env)
    print_debug(
        'SHELL REPLAY', " ".join(
            ["{}={}".format(k, v) for (k, v) in sorted(combined_env.items())]))
    print()
1362226
def parse(self, **kwargs):
        
        from aiida.engine import ExitCode
        from aiida.common import NotExistent

        try:
            out_folder = self.retrieved
        except NotExistent:
            return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER

        self._parse_stdout(out_folder)

        try:
            structure = self._parse_trajectory(out_folder)
            self.out('output_structure', structure)
        except Exception:  # pylint: disable=broad-except
            pass

        return ExitCode(0)
352081
def callPlaybook(self, playbook, ansibleArgs, wait=True, tags=["all"]):
        
        playbook = os.path.join(self.playbooks, playbook)  # Path to playbook being executed
        verbosity = "-vvvvv" if logger.isEnabledFor(logging.DEBUG) else "-v"
        command = ["ansible-playbook", verbosity, "--tags", ",".join(tags), "--extra-vars"]
        command.append(" ".join(["=".join(i) for i in ansibleArgs.items()]))  # Arguments being passed to playbook
        command.append(playbook)

        logger.debug("Executing Ansible call `%s`", " ".join(command))
        p = subprocess.Popen(command)
        if wait:
            p.communicate()
            if p.returncode != 0:
                # FIXME: parse error codes
                raise RuntimeError("Ansible reported an error when executing playbook %s" % playbook)
172406
private String resolveVariables(String name) {
		// Replace __variable__ with ${variable} and then evaluate the name as a groovy string
		String outName = "";
		int startPos = 0;
		int pos = name.indexOf("__", startPos);
		while (pos != -1) {
			outName += name.substring(startPos, pos);
			int endPos = name.indexOf("__", pos + 2);
			String variableName = name.substring(pos + 2, endPos);
			Object variableValue = model.resolveParameter(variableName, null);
			if (variableValue == null) {
				logWarn("Found no filepath variable __" + variableName + "__! Will use default value: " + variableName);
				variableValue = variableName;
			}
			logDebug("Found filepath variable: " + variableName + " = " + variableValue);
			outName += variableValue;
			startPos = endPos + 2;

			// Look for the next variable
			pos = name.indexOf("__", startPos);
		}
		outName += name.substring(startPos);
		logDebug("Resolved filepath [" + name + "] to [" + outName + "]");
		return outName;
	}
545563
def parse_args(args) #:nodoc:
      remapping = {}
      for arg in args
        splited = arg.split(':=')
        if splited.length == 2
          key, value = splited
          if key == '__name'
            @node_name = resolve_name(value)
          elsif key == '__ip'
            @host = value
          elsif key == '__hostname'
            @host = value
          elsif key == '__master'
            @master_uri = value
          elsif key == '__ns'
            @ns = value
          elsif key[0] == '_'[0]
            # local name remaps
            key[0] = '~'
            remapping[resolve_name(key)] = convert_if_needed(value)
          else
            # remaps
            remapping[key] = convert_if_needed(value)
          end
        end
      end
      remapping
    end
1158995
def _parse_args(args: List[str]) -> ProjectRunConfig:
    
    parser = argparse.ArgumentParser(prog="gitlab-get-variables", description="Tool for getting a GitLab project's "
                                                                              "build variables")
    add_common_arguments(parser, project=True)
    arguments = parser.parse_args(args)
    return ProjectRunConfig(project=arguments.project, url=arguments.url, token=arguments.token, debug=arguments.debug)
233070
def _parse_line_vars(self, line):
        
        key_values = {}

        # Undocumented feature allows json in vars sections like so:
        #   [prod:vars]
        #   json_like_vars=[{'name': 'htpasswd_auth'}]
        # We'll try this first. If it fails, we'll fall back to normal var
        # lines. Since it's undocumented, we just assume some things.
        k, v = line.strip().split('=', 1)
        if v.startswith('['):
            try:
                list_res = ihateyaml.safe_load(v)
                if isinstance(list_res[0], dict):
                    key_values = list_res[0]
                    return key_values
            except ValueError:
                pass

        # Guess it's not YAML. Parse as normal host variables
        tokens = shlex.split(line.strip())
        key_values = self._parse_vars(tokens)
        return key_values
1291757
def _get_clstr_outfile(self):
        """"""
        if self.Parameters['-o'].isOn():
            return ''.join([self.Parameters['-o'].Value, '.clstr'])
        else:
            raise ValueError, "No output file specified"
794078
def get_cmdline_varargs(argv=None):
    
    if argv is None:
        argv = sys.argv
    scriptname = argv[0]
    if scriptname == '':
        # python invoked by iteself
        pos_start = 0
        pos_end = 0
    else:
        pos_start = pos_end = 1
        for idx in range(pos_start, len(argv)):
            if argv[idx].startswith('-'):
                pos_end = idx
                break
        else:
            pos_end = len(argv)
    cmdline_varargs = argv[pos_start:pos_end]
    return cmdline_varargs