子流程只允许一个输入

时间:2016-10-30 22:36:41

标签: python subprocess

我使用子进程与交互式命令行应用程序进行通信,但在将第一个命令发送到应用程序后,所有其他输入似乎都没有传递给子进程。谁能告诉我我的错误在哪里?

以下是代码:

from subprocess import Popen, PIPE, STDOUT
from threading import Thread
from queue import Queue, Empty
import time


class Prolog(object):
    def __init__(self):
        """
        Opens a subprocess running swi-prolog and reads all the header stuff that it writes
        """
        self.prolog = Popen(r"C:\Program Files\swipl\bin\swipl.exe", stdin=PIPE, stdout=PIPE, stderr=STDOUT, bufsize=1)

        def enqueue_output(out, queue):
            for line in iter(out.readline, b''):
                queue.put(line)
            out.close()

        # This thread runs in the background as long as the program is running it enqueues all the output from Prolog
        self.q = Queue()
        t = Thread(target=enqueue_output, args=(self.prolog.stdout, self.q))
        t.daemon = True  # thread dies with the program
        t.start()

        out = True
        while out:
            out = self.get_line()

    def get_line(self):
        """
        read line without blocking
        :return: the next line in the output, else False if no more output
        """
        try:
            line = self.q.get(timeout=.1)  # or q.get(timeout=.1)
        except Empty:
            return False
        else:  # got line
            return line

    def send_query(self, query):
        """
        Sends a query to the Prolog shell
        :param query: string containing the query to be sent to the prolog shell
        :return: None
        """
        query = query + "\n"
        query = bytes(query, encoding="utf-8")
        self.prolog.stdin.write(query)
        self.prolog.stdin.flush()

    def get_output(self):
        output = self.get_line()
        if not output:
            return False
        else:
            return output[:-2]

    def query(self, query):
        output = []
        self.send_query(query)
        temp = self.get_output()
        print(temp)

        while not temp:
            time.sleep(.1)
            temp = self.get_output()

        output.append(temp)

        while not temp == b'true.' and not temp == b'false.':
            self.send_query(";")
            temp = self.get_output()
            print(temp)

            while not temp:
                time.sleep(.1)
                temp = self.get_output()

            output.append(temp)

        print(output)


if __name__ == "__main__":
    p = Prolog()

    p.query('[\"GCD.pl\"].')
    p.get_output()
    p.query("permut([a, b, c], X).")

问题出现在第二次调用p.query期间。该命令似乎根本没有传递给shell,所以从来没有任何输出,所以程序只是卡在"而不是临时"循环查询方法。

0 个答案:

没有答案