Using python's eval() vs. ast.literal_eval()?

前端 未结 6 1241
情深已故
情深已故 2020-11-21 06:39

I have a situation with some code where eval() came up as a possible solution. Now I have never had to use eval() before but, I have come across p

6条回答
  •  名媛妹妹
    2020-11-21 07:12

    Python's eager in its evaluation, so eval(input(...)) (Python 3) will evaluate the user's input as soon as it hits the eval, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval user input.

    Use ast.literal_eval.


    As an example, entering this at the prompt could be very bad for you:

    __import__('os').system('rm -rf /a-path-you-really-care-about')
    

提交回复
热议问题