python类shlex()的实例源码

win32rcparser.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def currentQuotedString(self):
        # Handle quoted strings - pity shlex doesn't handle it.
        assert self.token.startswith('"'), self.token
        bits = [self.token]
        while 1:
            tok = self.getToken()
            if not tok.startswith('"'):
                self.ungetToken()
                break
            bits.append(tok)
        sval = "".join(bits)[1:-1] # Remove end quotes.            
        # Fixup quotes in the body, and all (some?) quoted characters back
        # to their raw value.
        for i, o in ('""', '"'), ("\\r", "\r"), ("\\n", "\n"), ("\\t", "\t"):
            sval = sval.replace(i, o)
        return sval
win32rcparser.py 文件源码 项目:purelove 作者: hucmosin 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def parseH(self, file):
        lex = shlex.shlex(file)
        lex.commenters = "//"
        token = " "
        while token is not None:
            token = lex.get_token()
            if token == "" or token is None:
                token = None
            else:
                if token=='define':
                    n = lex.get_token()
                    i = int(lex.get_token())
                    self.ids[n] = i
                    if i in self.names:
                        # Dupe ID really isn't a problem - most consumers
                        # want to go from name->id, and this is OK.
                        # It means you can't go from id->name though.
                        pass
                        # ignore AppStudio special ones
                        #if not n.startswith("_APS_"):
                        #    print "Duplicate id",i,"for",n,"is", self.names[i]
                    else:
                        self.names[i] = n
                    if self.next_id<=i:
                        self.next_id = i+1
flowsynth.py 文件源码 项目:flowsynth 作者: secureworks 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, synfiledata):

        #init
        self.instructions = []
        self.dnscache = {}

        lexer = list(shlex.shlex(synfiledata))
        itr_ctr = 0
        while len(lexer) > 0:
            token = lexer[0]
            #should be the start of a new line
            if (token.lower() == 'flow'):
                (flowdecl, lexer) = self.lex_flow(lexer[1:])
                self.instructions.append(flowdecl)
            else:
                #treat as an event
                (eventdecl, lexer) = self.lex_event(lexer)
                self.instructions.append(eventdecl)
            itr_ctr = itr_ctr + 1
sch.py 文件源码 项目:KiField 作者: xesscorp 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, data):
        self.shape = {}
        self.unit = {}
        self.fields = []
        for line in data:
            line = line.replace('\n', '')
            s = shlex.shlex(line)
            s.whitespace_split = True
            s.commenters = ''
            s.quotes = '"'
            line = list(s)
            # select the keys list and default values array
            if line[0] in self._KEYS:
                key_list = self._KEYS[line[0]]
                values = line[1:] + ['' for n in range(len(key_list) - len(line[1:]))]
            if line[0] == 'S':
                self.shape = dict(zip(key_list,values))
            elif line[0] == 'U':
                self.unit = dict(zip(key_list,values))
            elif line[0][0] == 'F':
                key_list = self._F_KEYS
                values = line + ['' for n in range(len(key_list) - len(line))]
                self.fields.append(dict(zip(key_list,values)))
cronvar.py 文件源码 项目:DevOps 作者: YoLoveLife 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def parse_for_var(self, line):
        lexer = shlex.shlex(line)
        lexer.wordchars = self.wordchars
        varname = lexer.get_token()
        is_env_var = lexer.get_token() == '='
        value = ''.join(lexer)
        if is_env_var:
            return (varname, value)
        raise CronVarError("Not a variable.")
shell_completion.py 文件源码 项目:globus-cli 作者: globus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def safe_split_line(inputline):
    parser = shlex.shlex(inputline, posix=True)
    parser.whitespace_split = True
    res = []
    # track whether or not we're looking at quoted text -- it should suppress a
    # lot of types of completion if we see an open quote without a close quote
    quoted = False
    try:
        for val in parser:
            res.append(val)
    # No closing quotation
    except ValueError:
        quoted = True
    # grab the last token from the shlexer
    if parser.token:
        res.append(parser.token)
    return res, quoted
window.py 文件源码 项目:libtmux 作者: tony 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def rename_window(self, new_name):
        """Return :class:`Window` object ``$ tmux rename-window <new_name>``.

        :param new_name: name of the window
        :type new_name: str

        """

        import shlex
        lex = shlex.shlex(new_name)
        lex.escape = ' '
        lex.whitespace_split = False

        try:
            self.cmd(
                'rename-window',
                new_name
            )
            self['window_name'] = new_name
        except Exception as e:
            logger.error(e)

        self.server._update_windows()

        return self
test_shlex.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def testQuote(self):
        safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
        unicode_sample = '\xe9\xe0\xdf'  # e + acute accent, a + grave, sharp s
        unsafe = '"`$\\!' + unicode_sample

        self.assertEqual(shlex.quote(''), "''")
        self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
        self.assertEqual(shlex.quote('test file name'), "'test file name'")
        for u in unsafe:
            self.assertEqual(shlex.quote('test%sname' % u),
                             "'test%sname'" % u)
        for u in unsafe:
            self.assertEqual(shlex.quote("test%s'name'" % u),
                             "'test%s'\"'\"'name'\"'\"''" % u)

# Allow this test to be used with old shlex.py
win32rcparser.py 文件源码 项目:remoteControlPPT 作者: htwenning 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def currentQuotedString(self):
        # Handle quoted strings - pity shlex doesn't handle it.
        assert self.token.startswith('"'), self.token
        bits = [self.token]
        while 1:
            tok = self.getToken()
            if not tok.startswith('"'):
                self.ungetToken()
                break
            bits.append(tok)
        sval = "".join(bits)[1:-1] # Remove end quotes.            
        # Fixup quotes in the body, and all (some?) quoted characters back
        # to their raw value.
        for i, o in ('""', '"'), ("\\r", "\r"), ("\\n", "\n"), ("\\t", "\t"):
            sval = sval.replace(i, o)
        return sval
win32rcparser.py 文件源码 项目:remoteControlPPT 作者: htwenning 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def parseH(self, file):
        lex = shlex.shlex(file)
        lex.commenters = "//"
        token = " "
        while token is not None:
            token = lex.get_token()
            if token == "" or token is None:
                token = None
            else:
                if token=='define':
                    n = lex.get_token()
                    i = int(lex.get_token())
                    self.ids[n] = i
                    if i in self.names:
                        # Dupe ID really isn't a problem - most consumers
                        # want to go from name->id, and this is OK.
                        # It means you can't go from id->name though.
                        pass
                        # ignore AppStudio special ones
                        #if not n.startswith("_APS_"):
                        #    print "Duplicate id",i,"for",n,"is", self.names[i]
                    else:
                        self.names[i] = n
                    if self.next_id<=i:
                        self.next_id = i+1
win32rcparser.py 文件源码 项目:CodeReader 作者: jasonrbr 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def currentQuotedString(self):
        # Handle quoted strings - pity shlex doesn't handle it.
        assert self.token.startswith('"'), self.token
        bits = [self.token]
        while 1:
            tok = self.getToken()
            if not tok.startswith('"'):
                self.ungetToken()
                break
            bits.append(tok)
        sval = "".join(bits)[1:-1] # Remove end quotes.            
        # Fixup quotes in the body, and all (some?) quoted characters back
        # to their raw value.
        for i, o in ('""', '"'), ("\\r", "\r"), ("\\n", "\n"), ("\\t", "\t"):
            sval = sval.replace(i, o)
        return sval
win32rcparser.py 文件源码 项目:CodeReader 作者: jasonrbr 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parseH(self, file):
        lex = shlex.shlex(file)
        lex.commenters = "//"
        token = " "
        while token is not None:
            token = lex.get_token()
            if token == "" or token is None:
                token = None
            else:
                if token=='define':
                    n = lex.get_token()
                    i = int(lex.get_token())
                    self.ids[n] = i
                    if i in self.names:
                        # Dupe ID really isn't a problem - most consumers
                        # want to go from name->id, and this is OK.
                        # It means you can't go from id->name though.
                        pass
                        # ignore AppStudio special ones
                        #if not n.startswith("_APS_"):
                        #    print "Duplicate id",i,"for",n,"is", self.names[i]
                    else:
                        self.names[i] = n
                    if self.next_id<=i:
                        self.next_id = i+1
click_completion.py 文件源码 项目:pipenv 作者: pypa 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def split_args(line):
    """Version of shlex.split that silently accept incomplete strings."""
    lex = shlex.shlex(line, posix=True)
    lex.whitespace_split = True
    lex.commenters = ''
    res = []
    try:
        while True:
            res.append(next(lex))
    except ValueError:  # No closing quotation
        pass
    except StopIteration:  # End of loop
        pass
    if lex.token:
        res.append(lex.token)
    return res
click_completion.py 文件源码 项目:pipenv 作者: pypa 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def do_bash_complete(cli, prog_name):
    comp_words = os.environ['COMP_WORDS']
    try:
        cwords = shlex.split(comp_words)
        quoted = False
    except ValueError:  # No closing quotation
        cwords = split_args(comp_words)
        quoted = True
    cword = int(os.environ['COMP_CWORD'])
    args = cwords[1:cword]
    try:
        incomplete = cwords[cword]
    except IndexError:
        incomplete = ''
    choices = get_choices(cli, prog_name, args, incomplete)

    if quoted:
        echo('\t'.join(opt for opt, _ in choices), nl=False)
    else:
        echo('\t'.join(re.sub(r"""([\s\\"'])""", r'\\\1', opt) for opt, _ in choices), nl=False)

    return True
delegator.py 文件源码 项目:pipenv 作者: pypa 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _expand_args(command):
    """Parses command strings and returns a Popen-ready list."""

    # Prepare arguments.
    if isinstance(command, STR_TYPES):
        splitter = shlex.shlex(command.encode('utf-8'))
        splitter.whitespace = '|'
        splitter.whitespace_split = True
        command = []

        while True:
            token = splitter.get_token()
            if token:
                command.append(token)
            else:
                break

        command = list(map(shlex.split, command))

    return command
test_shlex.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def testQuote(self):
        safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
        unicode_sample = '\xe9\xe0\xdf'  # e + acute accent, a + grave, sharp s
        unsafe = '"`$\\!' + unicode_sample

        self.assertEqual(shlex.quote(''), "''")
        self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
        self.assertEqual(shlex.quote('test file name'), "'test file name'")
        for u in unsafe:
            self.assertEqual(shlex.quote('test%sname' % u),
                             "'test%sname'" % u)
        for u in unsafe:
            self.assertEqual(shlex.quote("test%s'name'" % u),
                             "'test%s'\"'\"'name'\"'\"''" % u)

# Allow this test to be used with old shlex.py
configparser.py 文件源码 项目:Theano-Deep-learning 作者: GeekLiB 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def parse_config_string(config_string, issue_warnings=True):
    """
    Parses a config string (comma-separated key=value components) into a dict.
    """
    config_dict = {}
    my_splitter = shlex.shlex(config_string, posix=True)
    my_splitter.whitespace = ','
    my_splitter.whitespace_split = True
    for kv_pair in my_splitter:
        kv_pair = kv_pair.strip()
        if not kv_pair:
            continue
        kv_tuple = kv_pair.split('=', 1)
        if len(kv_tuple) == 1:
            if issue_warnings:
                TheanoConfigWarning.warn(
                    ("Config key '%s' has no value, ignoring it"
                        % kv_tuple[0]),
                    stacklevel=1)
        else:
            k, v = kv_tuple
            # subsequent values for k will override earlier ones
            config_dict[k] = v
    return config_dict
sch.py 文件源码 项目:Boms-Away 作者: Jeff-Ciesielski 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __init__(self, data):
        self.shape = {}
        self.unit = {}
        self.fields = []
        for line in data:
            line = line.replace('\n', '')
            s = shlex.shlex(line)
            s.whitespace_split = True
            s.commenters = ''
            s.quotes = '"'
            line = list(s)
            # select the keys list and default values array
            if line[0] in self._KEYS:
                key_list = self._KEYS[line[0]]
                values = line[1:] + ['' for n in range(len(key_list) - len(line[1:]))]
            if line[0] == 'S':
                self.shape = dict(zip(key_list,values))
            elif line[0] == 'U':
                self.unit = dict(zip(key_list,values))
            elif line[0][0] == 'F':
                key_list = self._F_KEYS
                values = line + ['' for n in range(len(key_list) - len(line))]
                self.fields.append(dict(zip(key_list,values)))
test_shlex.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def testQuote(self):
        safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
        unicode_sample = '\xe9\xe0\xdf'  # e + acute accent, a + grave, sharp s
        unsafe = '"`$\\!' + unicode_sample

        self.assertEqual(shlex.quote(''), "''")
        self.assertEqual(shlex.quote(safeunquoted), safeunquoted)
        self.assertEqual(shlex.quote('test file name'), "'test file name'")
        for u in unsafe:
            self.assertEqual(shlex.quote('test%sname' % u),
                             "'test%sname'" % u)
        for u in unsafe:
            self.assertEqual(shlex.quote("test%s'name'" % u),
                             "'test%s'\"'\"'name'\"'\"''" % u)

# Allow this test to be used with old shlex.py
Jail.py 文件源码 项目:libiocage 作者: iocage 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _run_hook(self, hook_name: str):

        key = f"exec_{hook_name}"
        value = self.config[key]

        if value == "/usr/bin/true":
            return

        self.logger.verbose(
            f"Running {hook_name} hook for {self.humanreadable_name}"
        )

        lex = shlex.shlex(value)  # noqa: T484
        lex.whitespace_split = True
        command = list(lex)

        return iocage.lib.helpers.exec(
            command,
            logger=self.logger,
            env=self.env
        )
__init__.py 文件源码 项目:WhatTheHack 作者: Sylphias 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def smartsplit(string, sep):
    """Split while allowing escaping.

    So far, this seems to do what I expect - split at the separator,
    allow escaping via \, and allow the backslash itself to be escaped.

    One problem is that it can raise a ValueError when given a backslash
    without a character to escape. I'd really like a smart splitter
    without manually scan the string. But maybe that is exactly what should
    be done.
    """
    assert string is not None   # or shlex will read from stdin
    if not six.PY3:
        # On 2.6, shlex fails miserably with unicode input
        is_unicode = isinstance(string, unicode)
        if is_unicode:
            string = string.encode('utf8')
    l = shlex.shlex(string, posix=True)
    l.whitespace += ','
    l.whitespace_split = True
    l.quotes = ''
    if not six.PY3 and is_unicode:
        return map(lambda s: s.decode('utf8'), list(l))
    else:
        return list(l)
__init__.py 文件源码 项目:WhatTheHack 作者: Sylphias 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parse_binary(cls, string):
        r"""
        Parse a string for a binary (executable). Allow multiple arguments
        to indicate the binary (as parsed by shlex).

        Return a list of arguments suitable for passing to subprocess
        functions.

        >>> ExternalTool.parse_binary('/usr/bin/lessc')
        ['/usr/bin/lessc']

        >>> ExternalTool.parse_binary('node node_modules/bin/lessc')
        ['node', 'node_modules/bin/lessc']

        >>> ExternalTool.parse_binary('"binary with spaces"')
        ['binary with spaces']

        >>> ExternalTool.parse_binary(r'binary\ with\ spaces')
        ['binary with spaces']

        >>> ExternalTool.parse_binary('')
        []
        """
        return shlex.split(string)
__init__.py 文件源码 项目:click-completion 作者: click-contrib 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def split_args(line):
    """Version of shlex.split that silently accept incomplete strings."""
    lex = shlex.shlex(line, posix=True)
    lex.whitespace_split = True
    lex.commenters = ''
    res = []
    try:
        while True:
            res.append(next(lex))
    except ValueError:  # No closing quotation
        pass
    except StopIteration:  # End of loop
        pass
    if lex.token:
        res.append(lex.token)
    return res
__init__.py 文件源码 项目:click-completion 作者: click-contrib 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def do_bash_complete(cli, prog_name):
    comp_words = os.environ['COMP_WORDS']
    try:
        cwords = shlex.split(comp_words)
        quoted = False
    except ValueError:  # No closing quotation
        cwords = split_args(comp_words)
        quoted = True
    cword = int(os.environ['COMP_CWORD'])
    args = cwords[1:cword]
    try:
        incomplete = cwords[cword]
    except IndexError:
        incomplete = ''
    choices = get_choices(cli, prog_name, args, incomplete)

    if quoted:
        echo('\t'.join(opt for opt, _ in choices), nl=False)
    else:
        echo('\t'.join(re.sub(r"""([\s\\"'])""", r'\\\1', opt) for opt, _ in choices), nl=False)

    return True
package_linter.py 文件源码 项目:package_linter 作者: YunoHost 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def read_file(file_path):
    f = open(file_path)
    # remove every comments and empty lines from the file content to avoid
    # false positives
    file = shlex.shlex(f, False)
    #file = filter(None, re.sub("#.*[^\n]", "", f.read()).splitlines())
    return file
fc_config.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _parse_flink_line(line, final_flags):
    """private"""
    lexer = shlex.shlex(line, posix = True)
    lexer.whitespace_split = True

    t = lexer.get_token()
    tmp_flags = []
    while t:
        t = _parse_flink_token(lexer, t, tmp_flags)

    final_flags.extend(tmp_flags)
    return final_flags
fc_config.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _parse_flink_line(line, final_flags):
    """private"""
    lexer = shlex.shlex(line, posix = True)
    lexer.whitespace_split = True

    t = lexer.get_token()
    tmp_flags = []
    while t:
        t = _parse_flink_token(lexer, t, tmp_flags)

    final_flags.extend(tmp_flags)
    return final_flags
fc_config.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _parse_flink_line(line, final_flags):
    """private"""
    lexer = shlex.shlex(line, posix = True)
    lexer.whitespace_split = True

    t = lexer.get_token()
    tmp_flags = []
    while t:
        t = _parse_flink_token(lexer, t, tmp_flags)

    final_flags.extend(tmp_flags)
    return final_flags
tools.py 文件源码 项目:sc-controller 作者: kozec 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def shsplit(s):
    """ Returs original list from what shjoin returned """
    lex = shlex.shlex(s, posix=True)
    lex.escapedquotes = b'"\''
    lex.whitespace_split = True
    return [ x.decode('utf-8') for x in list(lex) ]
parameterParser.py 文件源码 项目:BioQueue 作者: liyao001 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parameter_string_to_list(par):
    import shlex
    parameter_string = shlex.shlex(par)
    parameter_string.quotes = '"'
    parameter_string.whitespace_split = True
    parameter_string.commenters = ''
    parameters = list(parameter_string)
    return parameters


问题


面经


文章

微信
公众号

扫码关注公众号