Import Paramiko in Jython - java

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.

Related

Jython: Can not import python function in Java

I am trying to develop a simple Java application and I want it to use some Python code using Jython. I am trying to run a python method from a file and getting this error:
ImportError: cannot import name testFunction
Just trying a simple example so I can see where the problem is. My python file test.py is like this:
def testFunction():
print("testing")
And my Java class:
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("path_to_file\\test.py");
interpreter.exec("from test import testFunction");
So it can correctly find the module but behaves like there is no function called testFunction inside.
Execute script files as follows.
interpreter.execfile("path/to/file/test.py");
If you have functions declared in the script file then after executing the above statement you'll have those functions available to be executed from the program as follows.
interpreter.exec("testFunction()");
So, you don't need to have any import statement.
Complete Sample Code:
package jython_tests;
import org.python.util.PythonInterpreter;
public class RunJythonScript2 {
public static void main(String[] args) {
try (PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.execfile("scripts/test.py");
pyInterp.exec("testFunction()");
}
}
}
Script:
def testFunction():
print "testing"
Output:
testing

PyhtonInterpreter all imports are failing

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)

How to use imports in Jython, used as standalone jar?

I want to run a Java code, which is :
import org.python.util.PythonInterpreter;
public class PyConv {
public static void main(String[] args){
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("Test.py");
}
}
And the Test.py file;
import pandas
import numpy
df = pd.read_csv("Myfile.csv", header=0)
But I would get an error:
Exception in thread "main" Traceback (most recent call last):
File "Test.py", line 1, in <module>
import pandas
ImportError: No module named pandas
So, How would one import the required module, to make the code run?
And also I am using the Jython as a external jar in my java code. Is there any other way which would make my job simpler?

Python Interpreter in Jython

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')"));.

java using jython has wrong python version

Im trying to use java to run a python function through jython.jar. I'm using a python module that is downloaded from web which needs python 2.6 or higher. I'm pretty sure that my python is version 2.7.2. However, when I try to run the java program, it continues to report python 2.5 detected. How can I resolve this?
My code is:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
...
//cmd
String command = "\"xml\\" + name2 + "\"";
PythonInterpreter python = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("C:\\Python27\\Lib\\site-packages"));
python.execfile("work1.py");
}
}
}
}
And the error is:
Exception in thread "main" Traceback (most recent call last): File "work1.py", line 8, in <module>
import networkx as nx File "C:\Python27\Lib\site-packages\networkx\__init__.py", line 39, in <module>
raise ImportError(m % sys.version_info[:2]) ImportError: Python version 2.6 or later is required for NetworkX (2.5 detected). Java Result: 1
You need to use Jython 2.7b3, 2.7 beta adds language compatibility with CPython 2.7...
http://comments.gmane.org/gmane.comp.lang.jython.devel/6145
2.7 beta 4 will come in July and after that a feature freeze. I suggest you join the python-dev mailing list to stay aware of new releases. Hope this helps

Categories