为什么必须“执行"? (而不是"eval")用于Python导入语句? [英] Why must "exec" (and not "eval") be used for Python import statements?

查看:176
本文介绍了为什么必须“执行"? (而不是"eval")用于Python导入语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jython在Java内部运行一小段Python.如果我使用exec语句导入,则一切正常.

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 PythonInterpreter();
pi.exec("import re");
PythonObject o = pi.eval("re.match('abc', 'abc123')"); // returns a MatchObject
o = pi.eval("re.match('abc', 'def123')"); // returns Py.None

但是,如果我尝试将这两行结合在一起,那么一切都将变得混乱.这个:

If, however, I try to combine the two lines, all hell breaks loose. This:

PythonInterpreter pi = new PythonInterpreter();
pi.eval("import re"); // exception!
PythonObject o = pi.eval("re.match('abc', 'abc123')"); // never gets here
o = pi.eval("re.match('abc', 'def123')"); // ....

...引发异常"no viable alternative at input 'import'", ('<string>',1,0,'import re\n').

这很重要,因为理想情况下,我希望能够将整个脚本评估为单个字符串,而不必将导入分为多个单独的部分.难道我做错了什么?是否有另一种方法可以告诉Jython将整个脚本(包括导入)全部运行,然后将其返回给我"?这需要在运行时-不能将Python预编译到.class文件中.

This matters, because ideally I'd like to be able to eval a whole script as a single string, without having to break the imports out into a separate part. Am I doing something wrong? Is there another way to tell Jython "take this whole blob of script, including imports, and run it, then give me back a result"? This needs to be at runtime -- pre-compiling the Python into .class files is not an option.

推荐答案

问题是 eval 计算表达式返回某些结果,而 exec 在某些情况下执行语句. import是一个语句,而re.match()是一个表达式.

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.

这篇关于为什么必须“执行"? (而不是"eval")用于Python导入语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆