Im using jython 2.7.0 and everything is working except one thing: I cant import anything. I do the following:
PythonInterpreter.initialize(props, System.getProperties(), new String[]{script.getParams().toJSON(), script.getContext().toJSON()});
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(script.getPath());
interpreter.exec("import sys");
interpreter.exec("import json");
interpreter.exec("import random");
PyObject answerEvent = interpreter.eval("json.loads(sys.argv[0])");
PyObject answerContext = interpreter.eval("json.loads(sys.argv[1])");
PyObject answerResult = interpreter.eval("json.dumps(handler(sys.argv[0], sys.argv[1]))");
System.out.println("=====================================================================");
System.out.println(answerEvent.toString());
System.out.println(answerContext.toString());
System.out.println(answerResult.toString());
System.out.println("=====================================================================");
And it really does not matter which import I run, I always get the error:
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named json
or
Import Error: No module named random
How do I get the imports working.
EDIT
Sorry, my information was not completely correct: import sys is working without a problem. The other two imports arent.
EDIT 2
I tried a recommended workaround described here in the last post but the result was the same.
Fixed with the following:
interpreter.exec("import sys");
interpreter.exec("sys.path.append('/usr/lib/python2.7')");
interpreter.exec("import random");
interpreter.exec("import json");
I needed to point to the lib folder of python 2.7 (But I still dont know why)
Related
I am trying to import python paramiko module from java program. So for that i used jython. When i try to import paramiko from jython it gives below error,
Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
ImportError: No module named paramiko
Please advice me to import paramiko from jython.
public class jythonTest {
public static void main(String[] args) throws PyException {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("import sys");
interp.exec("import paramiko");
interp.exec("import time");
}
}
This might be because Jython doesn't read the Python packages from the place where you might have installed them in Python through CLI.
One way to solve your problem is to install Paramiko in during the execution of the code:
PythonInterpreter interp = new PythonInterpreter();
interp.exec("from pip._internal import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");
Or
PythonInterpreter interp = new PythonInterpreter();
interp.exec("from pip import main as pip_main");
interp.exec("pip_main(['install', 'paramiko'])")
interp.exec("import paramiko");
Refer to Installing python module within code for more ways to install packages in code depending on your python version. The above should hold good for Python 2.7, which is what I believe Jython is based on.
I'm using org.python.util.PythonInterpreter class to execute python code in java. Please find below the snippet of of my code.
PythonInterpreter pythonInterpreter = new PythonInterpreter(null, new PySystemState());
ByteArrayOutputStream outStream = new ByteArrayOutputStream(16384);
pythonInterpreter.setOut(outStream);
pythonInterpreter.setErr(outStream);
// execute the code
pythonInterpreter.exec(script);
String consoleOutput = outStream.toString();
outStream.flush();
System.out.println("Console output :- "+consoleOutput);
The problem with the above code is for the same script sometimes I get 'consoleOutput' empty. I'm not able to figure out the problem. For running the above code 1000 times, at least 4 times I get empty output.
On the other hand if I use the default constructor as shown below it works just fine
PythonInterpreter pythonInterpreter = new PythonInterpreter();
Digging more into the problem I found, setting the property python.site.import to false triggers this problem. This issue occurs in Jython standalone version 2.7.0. Updating to the June 2017 release of the standalone jar(2.7.1) fixes this issue.
i am using JPype in order to work with java classes in python.
I have a folder that contains multiple self-written .jar files.
I know how to import multiple .jar's on the long way:
...
CLASSPATH = "/path/to/jars/first.jar:/path/to/jars/second.jar"
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % CLASSPATH)
MYLIB= jpype.JPackage("org").mylib
MyClass = MYLIB.MyClass
myObj = MyClass()
This works fine, but i think there might be a better way.
I already tried this:
CLASSPATH = "/path/to/jars/*.jar"
and this:
CLASSPATH = "/path/to/jars/*"
In both cases following error occurs:
user#user:~/path/to/python/$ python test.py
Traceback (most recent call last):
File "test.py", line 23, in <module>
myObj = MyClass()
File "/usr/local/lib/python2.7/dist-packages/JPype1-0.6.2-py2.7-linux-x86_64.egg/jpype/_jpackage.py", line 60, in __call__
raise TypeError("Package {0} is not Callable".format(self.__name))
TypeError: Package org.mylib.MyClass is not Callable
My Question:
Is there any way to easily import a folder that contains multiple .jar's in JPype?
You can join the list of jar files with Python code without hardcoding
f'{str.join(":", ["path/to/jars/"+name for name in os.listdir("path/to/jars")])}'
All I'm trying to do is pass an argument to the python interpreter so it can be passed as an argument for a module.
E.g. I have the following defined in a py file:
def print_twice(test):
print test
print test
I want to pass it the argument "Adam", so I've tried:
// Create an instance of the PythonInterpreter
PythonInterpreter interp = new PythonInterpreter();
// The exec() method executes strings of code
interp.exec("import sys");
interp.exec("print sys");
PyCode pyTest = interp.compile("Adam", "C:/Users/Adam/workspace/JythonTest/printTwice.py");
System.out.println(pyTest.toString());
I've also tried:
interp.eval("print_twice('Adam')");
I've been using the following Jython API but I don't understand it well:
http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#compile%28java.lang.String,%20java.lang.String%29
I would be very grateful for your advices.
Thank you
This should work:
interp.exec("import YOUR_PYTHON_FILE.py");
interp.exec("YOUR_PYTHON_FILE.print_twice('Adam')");
Its equivalent in a python console is this:
>>> import YOUR_PYTHON_FILE.py
>>> YOUR_PYTHON_FILE.print_twice('Adam')
Adam
Adam
You shouldn't need to explicitly compile the script, just import it and the interpreter will take care of compilation. Something like this (assuming printTwice.py is in the working directory of your program:
interp.exec("from printTwice import print_twice");
interp.exec("print_twice('Adam')");
You don't need to use interp.eval on the second line assuming that print_twice does actually contain print statements; if it just returns a string then you probably want
System.out.println(interp.eval("print_twice('Adam')"));.
This question already has answers here:
Closed 12 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 ? ImportError: 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.