How do I execute a string containing Python code in Python?

后端 未结 14 2393
一向
一向 2020-11-22 02:42

How do I execute a string containing Python code in Python?

14条回答
  •  盖世英雄少女心
    2020-11-22 02:51

    For statements, use exec(string) (Python 2/3) or exec string (Python 2):

    >>> mycode = 'print "hello world"'
    >>> exec(mycode)
    Hello world
    

    When you need the value of an expression, use eval(string):

    >>> x = eval("2+2")
    >>> x
    4
    

    However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.

提交回复
热议问题