By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Executing Python interpreter from Java

P: n/a
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?

(Btw, I know about Jython and I do not want to use that for a whole
lot of reasons.)

Thanks a whole lot!

import java.util.*;

public class PythonShell {

// these are out here so the inner class can access them...
static BufferedReader in = null;
static boolean ok = true;

public static void main(String[] args) throws InterruptedException {
ProcessBuilder pb = new ProcessBuilder("python", "-i"); // force
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) {
if (started) p.destroy();

final Scanner userIn = new Scanner(;
final Thread mainthread = Thread.currentThread();

class ReaderThread implements Runnable {
public void run() {
try {
while (true) {
int c =;
if (c == -1) {
ok = false;
catch (IOException exc) {
ok = false;

// try to interrupt the other thread
try {;
} catch (IOException exc) {}

Thread rt = new Thread(new ReaderThread());

while (ok) {
try {
String input = userIn.nextLine();
catch (NoSuchElementException exc) {
ok = false;


from Tkinter import *
t = Tk()
print 'hi'


May 21 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.