4

这个简单的代码:

s = "it's a nice day..."
s = shlex.split(s)

会导致ValueError: No closing quotation错误:

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    s = shlex.split(s)
  File "C:\Python\Python35-32\lib\shlex.py", line 273, in split
    return list(lex)
  File "C:\Python\Python35-32\lib\shlex.py", line 263, in __next__
    token = self.get_token()
  File "C:\Python\Python35-32\lib\shlex.py", line 90, in get_token
    raw = self.read_token()
  File "C:\Python\Python35-32\lib\shlex.py", line 166, in read_token
    raise ValueError("No closing quotation")
ValueError: No closing quotation

我认为'是错误的。我该如何处理?我从文件中读取了这一行,所以我不能只\在每个引用或其他内容之前输入。

4

2 回答 2

5

您应该在拆分之前使用安全地转义读取输入。如果您检查链接上的文档,则与拆分兼容。 shlex.quote(s)quote

import shlex
s = "it's a nice day..."
sq = shlex.quote(s)
print(sq)          #  '\'it\'"\'"\'s a nice day...\''
shlex.split(sq)    # ["it's a nice day..."]

使用该quote功能还将保护您免受“注入攻击”,如果您要接受不受信任的(不是您自己的)输入,您应该注意这一点。rm -rf ~有关炸弹的示例,请参阅文档!

于 2019-08-13T19:13:44.177 回答
2

应该被解析为 shell 输入的字符串(shlex 可以)不能有未转义的'字符。您需要在输入中添加转义字符

x = shlex.split("it\\'s a nice day...")
print(x)

给出:

["it's", 'a', 'nice', 'day...']

\\您可以通过在输入中执行 a添加额外内容replace

s = s.replace("'", "\\'")
于 2019-08-13T19:12:44.027 回答