[英]Using set input for stdin based on output from stdout with python subprocess
[英]How to get output from stdout using python subprocess?
我正在尝试使用 python 的(3.8)子进程库与 swipl(Prolog 解释器)进行通信。 (我使用的是 MAC OSx)
更多关于 Prolog: https://www.swi-prolog.org
在线Prolog翻译: https://swish.swi-prolog.org
我希望能够将一堆事实和规则加载到知识库中。 另外,我希望能够在口译员中提出多个问题,然后得到答案。
我已经尝试过通信function,但由于第一次通话后通信线路关闭,因此无法满足能够多次发送和接收数据的要求。
现在,当我运行程序时,我认为它会在写入中加载,然后当它到达 stdout.read() 时,它会运行该行,然后停止。 不知道到底发生了什么以及如何获得呼叫的 output。
import os
import signal
import subprocess
# NOTE: stderr=subprocess.PIPE makes the swipl intro in terminal go away
p = subprocess.Popen('swipl', stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, universal_newlines=True)
# The communicate() method returns a tuple (stdoutdata, stderrdata).
p.stdin.write('assert(car(honda, 18000, red)).')
p.stdin.write('assert(car(toyota, 18000, white)).')
p.stdin.write('assert(car(ford, 25000, red)).')
p.stdin.write('assert(car(acura, 50000, white)).')
p.stdin.write('assert(car(bmw, 60000, red)).')
p.stdin.write('[user]. recommendcar(Age, Car) :- Age =< 25, car(Car, Cost, red), Cost =< 30000 .')
p.stdin.write('recommendcar(20, X).')
output = p.stdout.read()
print(output)
p.kill()
尝试:
p.stdin.write('assertz(car(honda, 18000, red)).')
p.stdin.write('assertz(car(toyota, 18000, white)).')
p.stdin.write('assertz(car(ford, 25000, red)).')
p.stdin.write('assertz(car(acura, 50000, white)).')
p.stdin.write('assertz(car(bmw, 60000, red)).')
p.stdin.write('assertz((recommendcar(Age, Car) :- Age =< 25, car(Car, Cost, red), Cost =< 30000)).')
p.stdin.write('recommendcar(20, X).')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.