开发者

Why does Jython not find this module? [duplicate]

开发者 https://www.devze.com 2023-02-12 00:02 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to run a python script from java?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to run a python script from java?

I am running a Python script using Jython and got this error:

Exception in thread "main" Traceback (innermost last): File "C:\Facebook\LoginPython\Facebook.py", line 5, in ? ImportErro开发者_C百科r: no module named cookielib

Why doesn't this work?


A little bit more about using Jython - had my share of problems with that as well. Note that this may not be the best way to do it, but it works fine for me.

I assume you want to call a function foo in module bar from your Java code that takes a string argument and returns a string:

    PythonInterpreter interpreter = new PythonInterpreter();
    // Append directory containing module to python search path and import it
    interpreter.exec("import sys\n" + "sys.path.append(pathToModule)\n" + 
    "from bar import foo");
    PyObject meth = interpreter.get("foo");
    PyObject result = meth.__call__(new PyString("Test!"));
    String real_result = (String) result.__tojava__(String.class);

The sys.path.append() part is only necessary if your module isn't part of the Python search path by default, which may very well be the problem if you get Import or Module not find errors. Also you need to cast the objects between the java and python versions, you'll need to look that up if necessary, so far I only needed primitive types that were easy to cast, not sure if it's as easy for arbitrary java objects.


Use Jython to run Python on the JVM. Use PyDev to develop with Python (or Jython) on Eclipse.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号