Running shell process - python interpreter
Hello,
I'm trying to write some Java code that will launch a python interpreter shell and pipe input/output back and forth from the interpreter's i/o streams and the Java program. The code posted below seems to work just fine under Mac OS X; however, under Windows XP (Java 1.6 and Python 2.5 installed) the program hangs when I give a command to import the Tkinter (Python GUI library) and create a top-level frame window.
Specifically, run the program as:
% java PythonShell
.... (loads Python and displays welcome message)
>>> from Tkinter import *
>>> t = Tk()
>>>
After this point a frame window pops up but anything you type further doesn't evoke any further response from the shell. There is a little hiccup that occurs when the Tkinter library is actually loaded (on both the Mac or Windows OS) and the window in which the java program is running loses the focus-- I guess that has something to do with the way the Tk windowing library is loading. I know on the Java documentation for Process it says that it may not work correctly with native windowing libraries on some OSs. If this is what is happening here, does anyone have any suggestions?
Thanks a whole lot!
nadeem
import java.io.*;
import java.util.*;
publicclass PythonShell{
// these are out here so the inner class can access them...
static BufferedReader in =null;
staticboolean ok =true;
publicstaticvoid main(String[] args)throws InterruptedException{
ProcessBuilder pb =new ProcessBuilder("python","-i");// force interactive
pb.redirectErrorStream(true);// combine stdout and stderr
Process p =null;
PrintStream out =null;
boolean started =false;
try{
p = pb.start();
started =true;
in =new BufferedReader(new InputStreamReader(p.getInputStream()));
out =new PrintStream(p.getOutputStream(),true);
}
catch (IOException exc){
exc.printStackTrace();
if (started) p.destroy();
return;
}
final Scanner userIn =new Scanner(System.in);
final Thread mainthread = Thread.currentThread();
class ReaderThreadimplements Runnable{
publicvoid run(){
try{
while (true){
int c = in.read();
if (c == -1){
ok =false;
break;
}
System.out.print((char)c);
}
}
catch (IOException exc){
ok =false;
}
// try to interrupt the other thread
userIn.close();
try{
System.in.close();
}catch (IOException exc){}
mainthread.interrupt();
}
}
Thread rt =new Thread(new ReaderThread());
rt.start();
while (ok){
try{
String input = userIn.nextLine();
out.println(input);
System.out.println(ok);
}
catch (NoSuchElementException exc){
ok =false;
}
}
p.destroy();
p.waitFor();
}
}
/*
Input:
from Tkinter import *
t = Tk()
print 'hi'
*/

