在Java中使用PythonInterpreter调用send2trash移文件至回收站报错
问题:Java中使用PythonInterpreter调用send2trash报错NameError
我希望在Java代码中通过PythonInterpreter将文件移入回收站,Python代码可正常运行,但Java代码执行报错,Python环境安装无误。
Python 可运行代码
from send2trash import send2trash send2trash('C:\Slides\dog.jpg')
Java 出错代码
import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter py = new PythonInterpreter(); py.eval("from send2trash import send2trash"); py.exec("send2trash('cat-2.jpg')"); } }
报错信息
Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
NameError: name 'send2trash' is not defined
解决方法
问题核心是eval和exec的作用域不共享:eval执行导入操作后,不会自动将导入的函数注册到exec使用的全局命名空间中。可以用以下几种方式解决:
方法1:在同一条exec语句中完成导入和调用
将导入和调用逻辑放在同一个exec里,确保作用域一致:
import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter py = new PythonInterpreter(); py.exec("from send2trash import send2trash\n" + "send2trash('cat-2.jpg')"); } }
方法2:显式将导入的函数加入全局命名空间
通过eval获取函数对象,再用set方法将其存入PythonInterpreter的全局命名空间:
import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter py = new PythonInterpreter(); PyObject send2trashFunc = py.eval("from send2trash import send2trash; send2trash"); py.set("send2trash", send2trashFunc); py.exec("send2trash('cat-2.jpg')"); } }
方法3:用exec执行导入语句
直接用exec执行导入,导入的函数会自动进入全局命名空间:
import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) { PythonInterpreter py = new PythonInterpreter(); py.exec("from send2trash import send2trash"); py.exec("send2trash('cat-2.jpg')"); } }
内容的提问来源于stack exchange,提问作者Vitalij Victor
相关产品推荐
相关产品推荐

