subprocess.Popen() stdin problems
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-e开发者_如何学Crr redirection. How would i solve this problem using Popen, or maybe a completely different method
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.
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
精彩评论