I have written python code to invoke .java file, compile it & execute it using python. I'm using following python code
import os
import os.path,subprocess
from subprocess import STDOUT,PIPE
path='Location where my .java file is'
os.chdir(path)
def compile_java(java_file):
subprocess.check_call(['javac', java_file])
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = ['java', java_class]
compile_java('Hello.java')
execute_java("Hello")
My .java file contains simple hello world code. The code is given below
public class Hello {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
My python code is running successfully but I'm not getting "Hello World" message in my python console. Can you please help me to print java output(Hello World) in my python console?
Thanks in advance
You can execute the command using popen:
def execute_java(java_file):
java_class,ext = os.path.splitext(java_file)
cmd = 'java '+ java_class
f = os.popen(cmd)
print f.read()
Related
My application requires a series of values to be calculated using spark and i'm trying to make it metadata driven.
[
{
key : "myKeyName",
logic : "scala script"
}
...
]
I have a json that resembles above, which will be submitted with the "app.jar" to Spark. In the main() of spark job, I'm looking to load this json and execute the "logic" script in spark and get the value for the key. I think SparkContext.submitJob() is what I wan't but I'm not sure. Still looking for solutions in the web. Any help is deeply appreciated, thanks in advance.
The bundled jar is submitted to spark via SparkLauncher:
final SparkLauncher launcher = new SparkLauncher()
.setAppResource("path/to/app.jar")
.setMainClass("the.main.class")
.setMaster("spark.master")
.setConf(SparkLauncher.DRIVER_MEMORY, "3g");
//add the other dependent jar files
launcher.startApplication();
PS: the Spark application is implemented as a service in Docker.
Figured it out by myself.
//...
import scala.tools.nsc.interpreter.IMain;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
//...
private void scalaJob(SparkSession sparkSession, Dataset<Row> someData){
ScriptEngine e = new ScriptEngineManager().getEngineByName("scala");
//tell scala to use the classpath same as java
((IMain)e).settings().classpath().append(System.getProperty("java.class.path"));
//passing on some foo and bar
e.getContext().setAttribute("sparkSession",sparkSession, ScriptContext.ENGINE_SCOPE);
e.getContext().setAttribute("someData",someData, ScriptContext.ENGINE_SCOPE);
try {
//hello world
String script = "object HelloWorld {\n";
script += "def main(args: Array[String]): Unit = {\n";
script += "println(\"Hello, world!\")\n";
script += "}\n";
script += "}\n";
script += "HelloWorld.main(Array())";
e.eval(script);
//some serious work
script = "import org.apache.spark.sql.SparkSession\n";
script += "import org.apache.spark.sql.Dataset\n"
script += "import org.apache.spark.sql.Row\n";
script += "val processedData = someData.asInstanceOf[Dataset[Row]]\n";
script += "processedData.show(false)\n"
script += "processedData\n";
//getting back the result of serious work
Dataset<Row> ds = (Dataset<Row>) e.eval(script);
ds.show();
} catch (ScriptException ex) {
ex.printStackTrace();
System.exit(1);
}
}
The script is loaded from the json metadata.
PS: This is just an example, not the production code.
Iv been looking into embedding jython into my java program to allow users to script in python. However i want to print the output of their python scripts into a java text box in my program. But i cannot find a way to embed the output of the jython engine:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngine pyEngine = new ScriptEngineManager().getEngineByName("python");
Object Pyoutput = pyEngine.eval("2*3");
System.out.println(Pyoutput.toString());
}
}
I tried this to get the output of eval.
This outputs 6
Which is correct however when i try the same from a print statement:
Object Pyoutput = pyEngine.eval("print('Hello World')");
System.out.println(Pyoutput.toString());
the output is null when it should be Hello World. Is there a way to print the entire output/terminal content of a script that has been eval/exec by jython?
You can set a Writer for the scripts to use through the engines ScriptContext. For example:
ScriptEngine pyEngine = new ScriptEngineManager().getEngineByName("python");
StringWriter sw = new StringWriter();
pyEngine.getContext().setWriter(sw);
pyEngine.eval("print('Hello World')");
System.out.println(sw.toString());
Prints
Hello World
Hello I am using AutoIt in my Java Program using autoitx4java.Below is the code I am using:
import java.io.File;
import autoitx4java.AutoItX;
import com.jacob.com.LibraryLoader;
public class MyTest {
public static void main(String[] args) throws InterruptedException{
// TODO Auto-generated method stub
String jacobDllVersionToUse;
if (jvmBitVersion().contains("32")){
jacobDllVersionToUse = "jacob-1.18-x86.dll";
}
else {
jacobDllVersionToUse = "jacob-1.18-x64.dll";
}
File file = new File("lib", jacobDllVersionToUse);
System.setProperty(LibraryLoader.JACOB_DLL_PATH, file.getAbsolutePath());
AutoItX x = new AutoItX();
// System.out.println(file.getAbsolutePath());
x.run("cmd.exe");
}
private static String jvmBitVersion() {
// TODO Auto-generated method stub
System.out.println(System.getProperty("sun.arch.data.model"));
return System.getProperty("sun.arch.data.model");
}
}
When i run this program nothing happens and there is no error also.This also happens if i replace cmd.exe with notepad.exe.
However when i replace cmd.exe with calc.exe calculator launches.
I am new to AutoIt and using the below link to setup AutoIt with Java:
http://www.joecolantonio.com/2014/07/02/selenium-autoit-how-to-automate-non-browser-based-functionality/
This might be that run does not find cmd and notepad if its looking in the wrong path, could be a 32/64 bit issue. Or the process is started but window is not visible, so check if the process runs in task manager.
Run will not give an error, but it will return "0 and set #error to non-zero". If it succeeds, it will return "the PID of the process that was launched"
https://www.autoitscript.com/autoit3/docs/functions/Run.htm
To see if it succeeds, try this and see if it returns a pid:
MsgBox(0, "test", run("cmd.exe"))
If it returns 0 it probably means that program was not found. Try full filepath, for example:
MsgBox(0, "test", run("cmd.exe", "C:\Windows\System32\"))
If a pid is returned and the process is running but you see no window, try to add #SW_SHOW flag:
run("cmd.exe", "", #SW_SHOW)
run("cmd.exe", "", #SW_SHOW) worked !
Hi to open the notepad you can use the below code. As this is working for me.
AutoItX x = new AutoItX();
x.run("notepad.exe","",AutoItX.SW_SHOW);
x.winActivate("Untitled - Notepad");
x.winWaitActive("Untitled - Notepad");
x.send("This is some text");
I am using Rserve to access an R script through my Java project. The java code asks for a user input to enter the file location and stores in a String variable. This variable is then passes through to the R function which should read the file location perform some processes and then create a new folder and write the processed data in individual files and then print out on the console that all the files have been generated. I initially checked the R connection with a smaller version of the program and it worked. But, when I include the steps to write data to files, it shows the following error:
Enter the file path:
/home/workspace/TestR/test_file
Exception in thread "main" org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:234)
at testMain.main(testMain.java:23)
Moreover, the code also does not print any statements on the console which have to be printed via R from the Rscript. Here is the Java code:
import java.util.Scanner;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class testMain {
static String dirPath;
public static void main(String[] args) throws REXPMismatchException, REngineException {
// For user input
Scanner scanner = new Scanner(System.in );
System.out.println("Enter the file path: ");
dirPath = scanner.nextLine();
RConnection c = new RConnection();
// source the Palindrome function
c.eval("source('/home/workspace/TestR/Main.R')");
REXP valueReturned = c.eval("Main(\""+dirPath+"\")");
//c.eval("Main(\""+dirPath+"\")");
System.out.println(valueReturned.length());
}
}
And, here is the R script:
Main <- function(FILE_PATH)
{
## load libraries
library(MALDIquant)
library(MALDIquantForeign)
library(dcemriS4)
require(gridExtra) # also loads grid
library(lattice)
library(fields)
library(matlab)
library(rJava)
#Call the source files of the function which this script will use
source('/home/workspace/TestR/importAnalyzeFormat.R', echo=TRUE)
source('/home/workspace/TestR/exportFile.R', echo=TRUE)
source('/home/workspace/TestR/readRecalibratedSpectra.R', echo=TRUE)
spectralDataObjects <- importAnalyzeFormat(FILE_PATH)
p <- detectPeaks(spectralDataObjects, method="MAD", halfWindowSize=1, SNR=1)
# Assign the p to preprocessedDataObjects
preprocessedDataObjects<-p
dir.create("PreprocessedSpectra", showWarnings = FALSE)
setwd("PreprocessedSpectra")
for(i in 1:length(preprocessedDataObjects))
{
coordinateValue<-metaData(preprocessedDataObjects[[i]])
coordinates<-coordinateValue$imaging$pos
mzValues<-mass(preprocessedDataObjects[[i]])
intensityValues<-intensity(preprocessedDataObjects[[i]])
exportFile(coordinates,mzValues,intensityValues)
}
print("Files exported. Program will now terminate")
print("############################################################")
return(preprocessedDataObjects)
}
Can someone please help me?
You have an error in your script, a 127 means that there is a parse exception.
If you use something like this it will print out the error in the script.
c is the rserve connection in this case.
c.assign(".tmp.", myCode);
REXP r = c.parseAndEval("try(eval(parse(text=.tmp.)),silent=TRUE)");
if (r.inherits("try-error")) System.err.println("Error: "+r.toString())
else { // success .. }
Error code 127 means parsing exception.
Change your line:
c.eval("source('/home/workspace/TestR/Main.R')");
to
c.eval("source(\"/home/workspace/TestR/Main.R\")");
Now it is suppose to work.
I'm trying to run a Perl script file from java code but it's not working with me. I modified the Perl script and put the arguments in it instead of passing them via java code. The script works fine when running it from the command line but it's not working inside java code, always prints "wrong"!!. I wrote another Perl script (test.pl) and it's working but the desired script doesn't?? I'm working in netbeans7.3.1 (ubuntu).
Here is my code:
package program;
import java.io.*;
//import java.lang.ProcessBuilder;
/**
*
* #author seed
*/
public class Program {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException,Exception {
File input = new File("//home//seed//Downloads//MADA-3.2//sample");
FileOutputStream out = new FileOutputStream(input);
PrintWriter p = new PrintWriter(out);
String s = "قصدنا في هذا القول ذكر";
p.println(s);
p.close();
Process pro = Runtime.getRuntime().exec("perl /home/seed/Downloads/MADA+TOKAN.pl");
pro.waitFor();
if(pro.exitValue() == 0)
{
System.out.println("Command Successful");
}
else{
System.out.print("wrong");}
// TODO code application logic here
}
}
My guess is that some kind of string/path conversion issue.
I see utf8 strings in your code, maybe the path is converted to something.
The filename (MADA+TOKAN.pl) contain special char, it would be better MADAplusTOKAN.pl.
Also your string in script and in question are not the same: (MADA 3.2 != MADA-3.2)
perl MADA+TOKAN.pl config=/home/seed/Downloads/mada/MADA-3.2/config files/template.madaconfig file=/home/seed/Downloads/mada/MADA 3.2/inputfile
vs
perl MADA+TOKAN.pl config=/home/seed/Downloads/MADA-3.2/config-files/template.madaconfig file=/home/seed/Downloads/MADA-3.2/sample
It sounds like it is finding your perl script and executing it, since test.perl and MADA.perl run OK.
It does sound like the arguments being passed in to the perl script are not what was expected. Can you modify the perl script to echo all its input parameters to a file?