shlex.split()以单个字符串返回整个命令

时间:2019-05-07 14:59:24

标签: python string python-3.6 shlex

shlex.split()在输入字符串上未提供正确的输出。

在python解释器中,将输入值存储在变量中会产生预期的输出。

但是,如果我通过脚本执行,则shlex.split()输出不正确,并且输入字符串未在空白处分割。

>>> import shlex

>>> var = "/usr/bin/ansible-playbook --timeout=60 --module-path /var/sandeep> /playbooks/ --extra-vars '{ \"text\": \"DUMMY\", \"addition\": [\"1\", \"2\", \"3\", ], \"deletion\": [], \"update\": \"update\", \"path\": \"/var/sandeep\", }' /tmp/sandeep//tmp/example.yaml"
>>>
>>>
>>> shlex.split(var)

['/usr/bin/ansible-playbook', '--timeout=60', '--module-path', '/var/sandeep/playbooks/', '--extra-vars', '{ "text": "DUMMY", "addition": ["1", "2", "3", ], "deletion": [], "update": "update", "path": "/var/sandeep", }', '/tmp/sandeep//tmp/example.yaml']
def create_extra(text, extra_dict):
    extra = "'{{ \\\"text\\\": \\\"{}\\\", ".format(text)
    for key, value in extra_dict.items():
        if isinstance(value, list):
            extra += '\\\"{}\\\": ['.format(key)
            for item in value:
                extra += '\\\"{}\\\", '.format(item)
            extra += '], '
        elif isinstance(value, dict):
            extra += '\\\"{}\\\": {{'.format(key)
            for item_key, item_value in value.items():
                extra += '\\\"{}\\\": \\\"{}\\\", '.format(item_key, item_value)
            extra += "}, "
        else:
            extra += '\\\"{}\\\": \\\"{}\\\", '.format(key, value)
    extra += "}'"
    #print("extra: %s" % extra)
    return extra

extra_dict = {'addition': ["1", "2", "3"],
                   'deletion': [],
                   'update': 'update',
                   'path' : '/var/sandeep'
                  }


temp = create_extra("DUMMY", extra_dict)

"""create_extra function formats and return string"""

cmd = ('"/usr/bin/ansible-playbook ' +
        '--timeout=60 '  +
        '--module-path /var/sandeep/playbooks/ ' +
        '--extra-vars {} {}/{}"'.format(temp, "/tmp/sandeep", "/tmp/example.yaml"))

print(cmd)
print(shlex.split(cmd))
output of print(cmd)
"/usr/bin/ansible-playbook --timeout=60 --module-path /var/sandeep/playbooks/ --extra-vars '{ \"text\": \"DUMMY\", \"addition\": [\"1\", \"2\", \"3\", ], \"deletion\": [], \"update\": \"update\", \"path\": \"/var/sandeep\", }' /tmp/sandeep//tmp/example.yaml"


Expected results:
['/usr/bin/ansible-playbook', '--timeout=60', '--module-path', '/var/sandeep/playbooks/', '--extra-vars', '{ "text": "DUMMY", "addition": ["1", "2", "3", ], "deletion": [], "update": "update", "path": "/var/sandeep", }', '/tmp/sandeep//tmp/example.yaml']


Actual Results:
['/usr/bin/ansible-playbook --timeout=60 --module-path /var/sandeep/playbooks/ --extra-vars \'{ "text": "DUMMY", "addition": ["1", "2", "3", ], "deletion": [], "update": "update", "path": "/var/sandeep", }\' /tmp/sandeep//tmp/example.yaml']

我在这里想念什么吗?

1 个答案:

答案 0 :(得分:2)

由于字符串中包含文字class Card extends React.Component { render() { return ( <React.Fragment> <p>Card no. {this.props.card.id}</p> <input type="checkbox" onChange={e => { this.props.onChange(this.props.card.id); // Doesn't define it own onChange method and invokes the one passed down by the Parent. }} /> </React.Fragment> ); } } ,因此shlex的输出是完全正确的。

"

您的cmd = ('"/usr/bin/ansible-playbook ' + # ^- that right there '--timeout=60 ' + '--module-path /var/sandeep/playbooks/ ' + '--extra-vars {} {}/{}"'.format(temp, "/tmp/sandeep", "/tmp/example.yaml")) # and this right here -^ 显示如下:

print(cmd)

...您的字符串以"/usr/bin/ansible-playbook --timeout=60 --module-path /var/sandeep/playbooks/ --extra-vars whatever /tmp/sandeep//tmp/example.yaml" 开头,以"结尾,并且在由shell解析时使其成为单个文字字符串。


只需删除这些字符,问题就不再发生:

"

但是,您还有其他个严重的错误,因为字符串连接本质上不适合构建命令行。不必尝试完全采用这种方法,只需直接构建一个数组:

cmd = ('/usr/bin/ansible-playbook ' +
       '--timeout=60 '  +
       '--module-path /var/sandeep/playbooks/ ' +
       '--extra-vars {} {}/{}'.format(temp, "/tmp/sandeep", "/tmp/example.yaml"))

print(cmd)
print(shlex.split(cmd))

...然后cmd = ['/usr/bin/ansible-playbook', '--timeout=60', '--module-path', '/var/sandeep/playbooks/', '--extra-vars', temp, os.path.join('/tmp/sandeep', '/tmp/example.yml')] 或带有空格或文字引号的其他变量的值将不再破坏您的代码或允许注入任意参数。