2011-04-23 53 views
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() 

運行時沒有錯誤,但運行時無法在提示符處鍵入任何輸入。沒有字符或返回用戶類型出現,但打印正在運行的jar的輸出。我在尋找的是在終端類中輸入輸入,處理它,並將輸出提供給正在運行的java程序。淘寶互聯網後,我發現是subprocess.Popen(),但我無法找出stdin出err重定向。我將如何解決使用POPEN可能是完全不同的方法這個問題,或者subprocess.Popen()stdin問題

+0

不要將過程代碼直接放在類體中,比如'class test';使用它的功能/方法。 – jfs 2011-04-28 04:55:32

回答

0

這裏有一個類似的問題:

Python and subprocess input piping

在這種情況下,OP也運行在JVM和預期用戶輸入。我想你可以用select((sys.stdin,),(),())來代替你的while循環。當select()返回時,您應該有輸入以從其返回值讀取,然後管道到您的Popen對象。

0

我的問題最終的解決方案是改變while循環AJ建議

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) 

和改變POPEN調用

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

我也不得不改變殼= True參數。即使在我改變循環之後,這個簡單的參數就打破了一切