简体   繁体   English

subprocess.Popen()stdin问题

[英]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. 没有字符或返回的用户类型出现,但正在运行的jar的输出会打印出来。 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. 我正在寻找要执行的操作是在终端类中接受输入,对其进行处理,然后将输出提供给正在运行的Java程序。 After scouring the internet all I found is subprocess.Popen(), but i cant figure out the stdin-out-err redirection. 搜寻互联网后,我发现的只是subprocess.Popen(),但我无法弄清楚stdin-out-err重定向。 How would i solve this problem using Popen, or maybe a completely different method 我如何使用Popen或完全不同的方法解决此问题

Here is a similar question: 这是一个类似的问题:

Python and subprocess input piping Python和子流程输入管道

The OP in this case is also running a jvm and expecting user input. 在这种情况下,OP也正在运行jvm并期待用户输入。 I think you'd replace your while loop with a call to select((sys.stdin,),(),()) . 我认为您应该用select((sys.stdin,),(),())来代替while循环。 When select() returns you should have input to read from its return value and then pipe to your Popen object. select()返回时,您应该具有从其返回值读取的输入,然后通过管道传递到Popen对象。

The final solution to my problem was changing the while loop as AJ suggested 解决我的问题的最终方法是按照AJ的建议更改while循环

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 并更改Popen调用

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

I also had to change the shell=True argument. 我还必须更改shell = True参数。 Even after I changed the loop this simple argument broke everything 即使我改变了循环,这个简单的论点也打破了一切

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM