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
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.
So i wanted to use JSON library in my project but when i try to javac with a classpath of the json.jar
Used this on cmd :
javac -classpath json.jar main.java
and i get this error
error: package org.json does not exist
I dont know why ... then i made a more simple program to try and test if it runs
i get the same error ... I am using Atom for programming in Java .
The really simple program i tried to test :
import java.io.*;
import org.json.*;
public class main {
public static void main(String[] args){
JSONObject obj = new JSONObject();
System.out.println("Hello");
}
}
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?
I have a java class and a c# class. I want to run that C# class from my java class.
However I don't want to pass anything from java code to c# and also don't want anything in return from C# code, I just want to run that C# code.
I want to do something like shown in below classes
Java Class:
public void static main(String[] args){
System.out.println("Running Java code ");
// here need to call C# class
}
}
I want this code to be executed from above java program
using System;
class Program {
Console.WriteLine("Running C# code ");
}
}
You can run the C# program exe file from java code.
first compile the C#.NET program to get the Program.exe file then run the same Program.exe from java code as below:
public static void main(String[] args) throws IOException {
// TODO code application logic here
Process process;
process = new ProcessBuilder("C:\\ProjectsPath\\Program.exe").start();
}
Edit:
You can send the parameters to the exe file to be invoked by passing the arguments to the ProcessBuilder constructor as below:
Note : here im passing two argumenbts to Program.exe file Name and ID :
process = new ProcessBuilder("C:\\ProjectsPath\\Program.exe" , "Sudhakar","ID501").start();
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");
}
}