How to safely use exec() in Python?

后端 未结 2 933
甜味超标
甜味超标 2021-01-03 02:06

I have been tasked with building an application where an end user can have custom rules to evaluate whether a returned query results in a warning or alert (based on there ow

2条回答
  •  伪装坚强ぢ
    2021-01-03 02:54

    The only safe way to use eval or exec is not to use them.

    You do not need to use exec. Instead of building a string to execute, parse it into objects, and use that to drive your code execution.

    At its simplest, you can store functions in a dict, and use a string to select the function to call. If you're using python syntax, python provides all the utilities to parse itself, and you should use those.

提交回复
热议问题