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
Related
This question already has answers here:
Java interpreter? [closed]
(10 answers)
Closed 9 years ago.
For debug reasons, I want to be able to run code that is typed in through the console. For example:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
}
PLEASE DON'T ACTUALLY USE THIS
I was under the assumption you wanted to evaluate a string as Java code, not some scripting engine like Javascript, so
I created this on a whim after reading this, using the compiler API mark mentioned. It's probably very bad practice but it (somewhat) works like you wanted it to. I doubt it'll be much use in debugging since it runs the code in the context of a new class. Sample usage is included at the bottom.
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class main {
public static void runCode(String s) throws Exception{
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
File jf = new File("test.java"); //create file in current working directory
PrintWriter pw = new PrintWriter(jf);
pw.println("public class test {public static void main(){"+s+"}}");
pw.close();
Iterable fO = sjfm.getJavaFileObjects(jf);
if(!jc.getTask(null,sjfm,null,null,null,fO).call()) { //compile the code
throw new Exception("compilation failed");
}
URL[] urls = new URL[]{new File("").toURI().toURL()}; //use current working directory
URLClassLoader ucl = new URLClassLoader(urls);
Object o= ucl.loadClass("test").newInstance();
o.getClass().getMethod("main").invoke(o);
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
//command line
> System.out.println("hello");
hello
> System.out.println(3+2+3+4+5+2);
19
> for(int i = 0; i < 10; i++) {System.out.println(i);}
0
1
2
3
4
5
6
7
8
9
With the SimpleJavaFileObject you could actually avoid using a file, as shown here, but the syntax seems a bit cumbersome so I just opted for a file in the current working directory.
EDIT: Convert String to Code offers a similar approach but it's not fully fleshed out
If the code is in JavaScript then you can run it with JavaScript engine:
Object res = new ScriptEngineManager().getEngineByName("js").eval(str);
JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details
You can use the Java scripting API which is located in the Package javax.script. There you can include several scripting languages like bsh for example.
You can find a programmer's guide on the web page of Oracle.
Rhino, which is some kind of JavaScript is already included with the Oracle JVM.
For this you may want to look into Java Compiler API. I haven't studied much as to how this works, but it allows you to load a java file, compile and load the class in an already running system. Maybe it can be repurposed into accepting input from console.
For a general compiler you could use Janino which will allow you to compile and run Java code. The expression evaluator may help with your example.
If you are just looking to evaluate expressions while debugging then Eclispe has the Display view which allows you to execute expressions. See this question.
I'm a Java programer from China, recently I found a strange thing that the Windows console (eg. cmd.exe) seems to be able to display the characters that are not supported by current Code Page.
Could someone please tell me why?
There is example code and test result below.
import java.io.*;
import java.nio.charset.Charset;
public class EncodingTest {
public static void main(String[] args) {
System.out.println("jvm default charset:" + Charset.defaultCharset());
System.out.println(System.getProperty("file.encoding"));
PrintStream ps = new PrintStream(System.out, true);
ps.println("PrintStream测试");
System.out.println("测试哦,就是要测试啊啊");
System.out.println("中文测试");
System.out.println("--------------");
}
}
and here is screenshot of test result:
Screenshot
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()
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?
This question already has answers here:
Java interpreter? [closed]
(10 answers)
Closed 9 years ago.
For debug reasons, I want to be able to run code that is typed in through the console. For example:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
}
PLEASE DON'T ACTUALLY USE THIS
I was under the assumption you wanted to evaluate a string as Java code, not some scripting engine like Javascript, so
I created this on a whim after reading this, using the compiler API mark mentioned. It's probably very bad practice but it (somewhat) works like you wanted it to. I doubt it'll be much use in debugging since it runs the code in the context of a new class. Sample usage is included at the bottom.
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class main {
public static void runCode(String s) throws Exception{
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
File jf = new File("test.java"); //create file in current working directory
PrintWriter pw = new PrintWriter(jf);
pw.println("public class test {public static void main(){"+s+"}}");
pw.close();
Iterable fO = sjfm.getJavaFileObjects(jf);
if(!jc.getTask(null,sjfm,null,null,null,fO).call()) { //compile the code
throw new Exception("compilation failed");
}
URL[] urls = new URL[]{new File("").toURI().toURL()}; //use current working directory
URLClassLoader ucl = new URLClassLoader(urls);
Object o= ucl.loadClass("test").newInstance();
o.getClass().getMethod("main").invoke(o);
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
//command line
> System.out.println("hello");
hello
> System.out.println(3+2+3+4+5+2);
19
> for(int i = 0; i < 10; i++) {System.out.println(i);}
0
1
2
3
4
5
6
7
8
9
With the SimpleJavaFileObject you could actually avoid using a file, as shown here, but the syntax seems a bit cumbersome so I just opted for a file in the current working directory.
EDIT: Convert String to Code offers a similar approach but it's not fully fleshed out
If the code is in JavaScript then you can run it with JavaScript engine:
Object res = new ScriptEngineManager().getEngineByName("js").eval(str);
JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details
You can use the Java scripting API which is located in the Package javax.script. There you can include several scripting languages like bsh for example.
You can find a programmer's guide on the web page of Oracle.
Rhino, which is some kind of JavaScript is already included with the Oracle JVM.
For this you may want to look into Java Compiler API. I haven't studied much as to how this works, but it allows you to load a java file, compile and load the class in an already running system. Maybe it can be repurposed into accepting input from console.
For a general compiler you could use Janino which will allow you to compile and run Java code. The expression evaluator may help with your example.
If you are just looking to evaluate expressions while debugging then Eclispe has the Display view which allows you to execute expressions. See this question.