Why must “exec” (and not “eval”) be used for Python import statements?

前端 未结 3 1657
天命终不由人
天命终不由人 2020-12-30 07:15

I\'m trying to run a snippet of Python from within Java, using Jython. If I use an exec statement to import, everything works.

PythonInterpreter pi = new Py         


        
相关标签:
3条回答
  • 2020-12-30 07:33

    The problem is that eval evaluates expressions and returns some result, while exec executes statements in some context. import is a statement, while re.match() is an expression.

    0 讨论(0)
  • 2020-12-30 07:40

    Try this,

    eval("__import__('re').match('abc', 'abc123')")
    
    0 讨论(0)
  • 2020-12-30 07:44

    Here what do you mean by the result?

    I am assuming that it is some calculated value of your script. According to the documentation of 'exec' the code runs in the current scope. Hence you must be able to access the values of any new symbols that you have created inside exec statement.

    a = 20
    b = 10
    exec("c = a + b")
    print c
    

    The above code should print 30.

    0 讨论(0)
提交回复
热议问题