1
import subprocess
import threading
import StringIO

class terminal(threading.Thread):
    def run(self):
        self.prompt()

    def prompt(self):
        x = True
        while x:
            command = raw_input(':')
            x = self.interpret(command)

    def interpret(self,command):
        if command == 'exit':
            return False
        else:
            print 'Invalid Command'
        return True

class test(threading.Thread):
    command = 'java -jar ../bukkit/craftbukkit.jar'
    test = StringIO.StringIO()
    p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while (p.poll() == None):
        line = p.stderr.readline()
        if not line: break
        print line.strip()

term = terminal()
testcl = test()
term.start()
testcl.start()

This runs without error, however when running you cant type any input at the prompt. No characters or returns the user types appear, but the output of the running jar prints. What i'm looking for this to do is take input in the terminal class, process it, and feed output into the running java program. After scouring the internet all I found is subprocess.Popen(), but i cant figure out the stdin-out-err redirection. How would i solve this problem using Popen, or maybe a completely different method

joaquin
  • 82,968
  • 29
  • 138
  • 152
T_Mac
  • 223
  • 3
  • 10
  • don't put procedural code directly in a class body such as in the `class test` case; use functions/methods for that. – jfs Apr 28 '11 at 04:55

2 Answers2

0

Here is a similar question:

Python and subprocess input piping

The OP in this case is also running a jvm and expecting user input. I think you'd replace your while loop with a call to select((sys.stdin,),(),()). When select() returns you should have input to read from its return value and then pipe to your Popen object.

Community
  • 1
  • 1
AJ.
  • 27,586
  • 18
  • 84
  • 94
0

The final solution to my problem was changing the while loop as AJ suggested

while x:
    select.select((sys.stdin,),(),())
    a = sys.stdin.read(1)
    if not a == '\n':  
        sys.stdout.write(a)
        sys.stdout.flush()
    else:
        x = self.interpret(command)

and changing the Popen call

p = subprocess.Popen(command, shell=False, stdin = subprocess.PIPE)

I also had to change the shell=True argument. Even after I changed the loop this simple argument broke everything

T_Mac
  • 223
  • 3
  • 10