好的,所以我有一个使用calculate
命令的Discord机器人来评估数学表达式。我必须使用eval()
来评估它,因此我需要确保该字符串是安全的:
@bot.command()
async def calculate(ctx, *, operation=None):
# Some code
chars_allowed = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", ...)
for char in operation:
if char not in chars_allowed:
await ctx.send("Error: operation contains characters that are not allowed!")
return
result = eval(operation)
# Some code
我的问题是:以这种方式验证字符串是否更好,或者我可以使用:
@bot.command()
async def calculate(ctx, *, operation=None):
# Some code
result = eval(operation, {"__builtins__": {}}
# Some code
问题是我希望我的计算器具有很多功能,例如log,sqrt,floor,ceil,truncate,阶乘...
那么,第二种方法安全吗?