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?
Related
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
I'm trying to run multiple Jython files at the same time so that I can use my PC multiprocessor (specifically doing this in FDM in Hyperion's Workspace)
Is there any way I could do this?
I've tried to do it through Java, but it doesn't recognize the thread function, also tried through Python, and this version of Jython doesn't have the concurrency library, and not able to import it.
import os
import sys
from java.io import *
from java.util import *
from java import *
from java.lang import *
from threading import *
import java.util.logging.Level;
import java.util.logging.Logger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
new Thread() {
public void run() {
java.lang.Runtime.getRuntime().exec("python test1.py")
}
}.start()
new Thread() {
public void run() {
java.lang.Runtime.getRuntime().exec("python test2.py")
}
}.start()
new Thread() {
public void run() {
java.lang.Runtime.getRuntime().exec("python test3.py")
}
}.start()
Errors:
File "E:\Oracle\Middleware\EPMSystem11R1\products\FinancialDataQuality\Applications\FDMEE/data/scripts/custom/test.py", line 15
new Thread() {
^
SyntaxError: mismatched input 'Thread' expecting NEWLINE
You cannot use Java syntax in python code. Even if you're running it with Jython.
You can use the fact that Jython will convert python functions to Java functional interface.
from java.lang import Thread, Runtime
Thread(lambda: Runtime.getRuntime().exec("python test1.py")).start()
Thread(lambda: Runtime.getRuntime().exec("python test2.py")).start()
Thread(lambda: Runtime.getRuntime().exec("python test3.py")).start()
Pythonic way to do the same would be
import subprocess, threading
threading.Thread(target=lambda: subprocess.call(["python","test1.py"])).start()
threading.Thread(target=lambda: subprocess.call(["python","test2.py"])).start()
To be honest I would use multiprocessing instead of threading, but I am not sure if Jython supports it.
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 working on a quick interface to allow the use of the 9 DOF IMU in the rpi sense hat from java and I can't seem to get the python to work out. I have added the python 2.7 libraries into the sys path of the Jython environment but it still can't find this 'type_check' module.
Here is the java code:
PythonInterpreter interpreter;
SenseHat()
{
interpreter = new PythonInterpreter();
interpreter.exec("import sys");
interpreter.exec("sys.path.append('/usr/lib/python2.7/dist-packages')");
interpreter.exec("from sense_hat import SenseHat");
interpreter.exec("sense = SenseHat()");
PyObject result = interpreter.eval("sense.get_temperature()");
System.out.println(result.toString());
interpreter.close();
}
which attempts to use the RPI sense hat python API.
When executed I get this error:
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/sense_hat/__init__.py", line 2, in <module>
from .sense_hat import SenseHat, SenseHat as AstroPi
File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 7, in <module>
import numpy as np
File "/usr/lib/python2.7/dist-packages/numpy/__init__.py", line 153, in <module>
from . import add_newdocs
File "/usr/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
File "/usr/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 8, in <module>
from .type_check import *
ImportError: No module named type_check
How to invoke another java program by using Java Runtime.getRuntime.exec()?
its been told for executing a program using java program we can use Runtime.getRuntime().
Here is an example. I can open a notepad by using Runtime.getRuntime().exec("notepad.exe");
Can any one help me to execute a Java file. Thanks in advance!
You can execute a java file like this.
Runtime.getRuntime().exec("java Test");
This is assuming that your environmental variable(Path) for java & classpath have already been set, else you need to set them too!
In fact you can't execute directly a .java file. It needs to be compiled first. The compiling could be done using a System java compiler that can be obtained using ToolProvider and running with Runtime.getRuntime().exec(String). A sample would be something like:
import java.io.FileOutputStream;
import java.io.IOException;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class JavaTest {
public static void main(String[] args) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// creating a file, but you could load an existing one
FileOutputStream javaFile = new FileOutputStream("Test.java");
javaFile.write("public class Test { public static void main(String[] args) { javax.swing.JOptionPane.showMessageDialog(null, \"I'm here!\",\"Test\", 1);}}"
.getBytes());
// compiling it
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, System.out, System.err, "Test.java");
// running it
Runtime.getRuntime().exec("java Test");
}
}