这个简单的代码:
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:PythonPython35-32libshlex.py", line 273, in split
return list(lex)
File "C:PythonPython35-32libshlex.py", line 263, in __next__
token = self.get_token()
File "C:PythonPython35-32libshlex.py", line 90, in get_token
raw = self.read_token()
File "C:PythonPython35-32libshlex.py", line 166, in read_token
raise ValueError("No closing quotation")
ValueError: No closing quotation
我认为'
有错。我该如何处理?我从文件中读取了这一行,所以我不能在每个引号或其他内容之前键入。
在拆分之前,您应该使用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 ~
炸弹的示例,请参阅文档!
应该解析为 shell 输入的字符串(shlex 就是这样(不能有未转义的'
字符。您需要在输入中添加转义字符
x = shlex.split("it\'s a nice day...")
print(x)
给:
["it's", 'a', 'nice', 'day...']
您可以通过在输入中执行replace
来添加额外的\
:
s = s.replace("'", "\'")