When I run a python script, the output appears on the DOS ( command prompt in Windows ).
I want the output be displayed on a JAVA Application, i.e. on a window which contians JTextArea. The output should be same as that on the DOS.
So, How do I capture the output from the DOS and insert it into JAVA Application ??
(I tried storing output of the python script in a text file and then reading it using JAVA. But, in that case, the JAVA application waits for the script to finish running first and then displays the output. And, when the output is more than the screen size, a scroll bar appeears, so that I can see the entire output.)
After crowder's comment, I ran this code. but the output is always:
error: Process said:
import java.io.*;
import java.lang.*;
import java.util.*;
class useGobbler {
public static void main ( String args[] )
{
ProcessBuilder pb;
Process p;
Reader r;
StringBuilder sb;
int ch;
sb = new StringBuilder(2000);
try
{
pb = new ProcessBuilder("python","printHello.py");
p = pb.start();
r = new InputStreamReader(p.getInputStream());
while((ch =r.read() ) != -1)
{
sb.append((char)ch);
}
}
catch(IOException e)
{
System.out.println("error");
}
System.out.println("Process said:" + sb);
}
}
Can anyone tell me what am I doing wrong ??
You can connect to the error and inputStream, while Using
Runtime.exec()
oderProcessBuilder
.Examples can be found here: http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html
You can execute the process via a
ProcessBuilder
, which will give you aProcess
instance on which you can read the output via the stream returned fromgetInputStream
.Here's an example that runs the Python script
hello.py
and builds up its output in a string:You can then do whatever you like with the string, including putting it in the
JTextArea
like any other string. (You could use aBufferedReader
around theInputStreamReader
if you like, but you get the idea.)