【发布时间】:2014-05-27 13:36:26
【问题描述】:
当我在终端输入 jython 时,我得到:
Jython 2.2.1 on java1.7.0_51
我想在我的 java 代码中使用 NLTK POS。我按照@Vicent 在how to add module of python into java using jython jar 中的回答使用python 解释器,
package myjythonproject;
import org.python.util.PythonInterpreter;
public class MyJythonProject {
public static void main(String[] args) {
try
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("/home/vicent/foo.py");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
代码只有一处改动:
interp.execfile("/Users/ha/Desktop/Code.py");
没有错误但是Code.py的内容不显示(只是打印Hello world)。
if __name__ == "__main__":
print "Hello World";
我已经编辑了从终端到 jython lib 文件夹的系统路径。
我怎样才能让它工作?
更新:
在 if 语句之前添加print __name__ 之后 - 正如@MikeRixWolfe 所建议的那样 - 我得到了这个输出:
run:
main
BUILD SUCCESSFUL (total time: 1 second)
所以我将其编辑为 if __name__ == "main": 并且可以正常工作!
【问题讨论】:
-
也许输出可能不是你期望的,你可能需要调用 setErr 和 setOut。
-
如何在我添加的代码中使用 setErr?感谢您的回复@NESPowerGlove
-
PythonInterpreter API 应该告诉你jython.org/javadoc/org/python/util/PythonInterpreter.html
-
@Evanescence 很高兴听到将
__main__更改为main有效,事后看来,考虑到 java 的固有方法命名方案没有下划线,这完全有意义。
标签: java python netbeans-7 jython