Evaluating a mathematical expression in a string

前端 未结 11 1197
名媛妹妹
名媛妹妹 2020-11-21 05:01
stringExp = \"2^4\"
intVal = int(stringExp)      # Expected value: 16

This returns the following error:

Traceback (most recent call         


        
11条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 05:09

    Use eval in a clean namespace:

    >>> ns = {'__builtins__': None}
    >>> eval('2 ** 4', ns)
    16
    

    The clean namespace should prevent injection. For instance:

    >>> eval('__builtins__.__import__("os").system("echo got through")', ns)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 1, in 
    AttributeError: 'NoneType' object has no attribute '__import__'
    

    Otherwise you would get:

    >>> eval('__builtins__.__import__("os").system("echo got through")')
    got through
    0
    

    You might want to give access to the math module:

    >>> import math
    >>> ns = vars(math).copy()
    >>> ns['__builtins__'] = None
    >>> eval('cos(pi/3)', ns)
    0.50000000000000011
    

提交回复
热议问题