Python:我应该使用 eval、exec 还是 ..?
我试图使以下语句更加灵活:
for posting in page.findAll(attrs = {"id": re.compile(r'''post\d+''')}):
以下部分是从 CSV 文件动态检索并存储在字符串中(例如名为 test 的字符串)。 CSV 存储在安全位置,仅供管理员访问。
attrs = {"id": re.compile(r'''post\d+''')}
我可以使用 eval(test) 或 exec(test) 而不是仅测试来按如下方式集成变量吗?
for posting in page.findAll(test)):
I am trying to make the following statement more flexible:
for posting in page.findAll(attrs = {"id": re.compile(r'''post\d+''')}):
The following part is retrieved dynamically from a CSV file and stored in a string (for example the string called test). The CSV is stored in a secure location, accessible for admins only.
attrs = {"id": re.compile(r'''post\d+''')}
Can I integrate the variable as following by using an eval(test) or exec(test) in stead of just test?
for posting in page.findAll(test)):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想从用户输入运行代码(输入文件内容),您将需要
eval
或exec
,通过这些名称或其他名称(具体来说,您需要 < code>exec for 语句 - 赋值是一个语句)。但你不想(也不应该)这样做,因为这是邪恶的、不安全的、完全不必要的等等。删除赋值(仅存储字典)和
re.compile
调用,那么你可以在上面使用ast.literal_eval
并且你非常安全(你仍然应该捕获语法错误和其他可能出错的内容以显示合理的错误消息,但恶意代码应该接近不可能,而且也没有那么脏)。如果您认为需要,可以在加载后应用re.compile
。If you want to run code from user input (file contents are input), you'll need
eval
orexec
, by these names or some other (specifically, you needexec
for statements - assignment is a statement).But you don't want to (and shouldn't) do that, because that's evil, insecure, totally unnecessary, etc. Drop the assignment (just store the dict) and the
re.compile
call, then you can useast.literal_eval
on it and you're quite safe (you should still catch syntax errors and everything else that may go wrong to display a sensible error message, but malicious code should be close to impossible and it's not nearly as dirty). You can apply there.compile
after loading if you thing it's needed.除非您完全无法控制 CSV 源,否则应不惜一切代价避免此类加载。
pickle
模块将正则表达式保存为序列化数据(或者更好,只需保存字符串)json
模块将数据保存为 JSON 使用json
然后执行相反的操作,从文件中获取数据。
如果您无法控制 CSV 生成,请尝试使用
split
或re
模块手动提取数据。eval
和exec
是“最后机会解决方案”。除非没有其他方法,否则避免使用它们。Unless you have absolutely no control over the CSV source, avoid, at all cost these kinds of loading.
pickle
module (or better, just save the string)json
modulecsv
moduleThen do the opposite to get the data from the file.
If you can't control the CSV generation, try extracting the data manually using
split
or there
module.eval
andexec
are 'last chance solution'. Avoid using them unless you have no other ways.最安全的是 ast.literal_eval():
您可以将其用作:
The most secure is ast.literal_eval():
You can use it as:
两者都不是——这是Python——你可以编写一系列命名参数和所需的值来将函数作为字典调用。在这种情况下,键“attrs”的值的字典也是字典。调用函数时只需在字典名称前添加“**”即可:
Neither - this is Python - you can write a eries of named parameters and the desired values to call a function as dictionary. In this case, a dictionary which value fot the key "attrs" is also a dictionary. Just prepend to "**" to the dictionary name when calling the function: