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

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

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

14条回答
  •  心在旅途
    2020-11-22 02:47

    As the others mentioned, it's "exec" ..

    but, in case your code contains variables, you can use "global" to access it, also to prevent the compiler to raise the following error:

    NameError: name 'p_variable' is not defined

    exec('p_variable = [1,2,3,4]')
    global p_variable
    print(p_variable)
    

提交回复
热议问题