【发布时间】:2020-03-03 16:53:37
【问题描述】:
我正在尝试使用 python (3.8) 的子进程库与 swipl(Prolog 解释器)进行通信。 (我使用的是 MAC OSx)
更多关于 Prolog:https://www.swi-prolog.org
在线 Prolog 解释器:https://swish.swi-prolog.org
我希望能够将一堆事实和规则加载到知识库中。另外,我希望能够在口译员中提出多个问题,然后得到答案。
我已经尝试过通信功能,但由于第一次通话后通信线路已关闭,因此无法满足能够多次发送和接收数据的要求。
现在,当我运行程序时,我认为它会在写入中加载,然后当它到达 stdout.read() 时,它会运行该行,然后停止。不确定到底发生了什么以及如何获得调用的输出。
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()
【问题讨论】:
-
您可能已经找到了这个,但以防万一:pyswip 一个 Python - SWI-Prolog 桥。
-
谢谢保罗!我最初使用的是它,但我在设置它时遇到了很多错误。所以我的老师推荐我用这个
-
在 Flask 和 python 中使用 pyswip 也有太多问题。显然 pyswip 在多线程中表现不佳
标签: python python-3.x prolog subprocess swi-prolog