简体   繁体   English

如何使用 python 子进程从标准输出中获取 output?

[英]How to get output from stdout using python subprocess?

I am trying to use python's (3.8) subprocess library to communicate with swipl (Prolog interpreter).我正在尝试使用 python 的(3.8)子进程库与 swipl(Prolog 解释器)进行通信。 (I'm using MAC OSx) (我使用的是 MAC OSx)

More about Prolog: https://www.swi-prolog.org更多关于 Prolog: https://www.swi-prolog.org

Online Prolog interpreter: https://swish.swi-prolog.org在线Prolog翻译: https://swish.swi-prolog.org

I want to be able to load a bunch of facts and rules into the knowledge base.我希望能够将一堆事实和规则加载到知识库中。 Separately I want the ability to ask multiple questions in the interpreter and then receive the answer.另外,我希望能够在口译员中提出多个问题,然后得到答案。

I've already tried the communicate function, but it doesn't fulfill the requirement of being able to send and receive data multiple times since the communication line is close after the first call.我已经尝试过通信function,但由于第一次通话后通信线路关闭,因此无法满足能够多次发送和接收数据的要求。

Right now when I run the program I think it loads in the write and then when it gets to the stdout.read() it runs the line and then stalls out.现在,当我运行程序时,我认为它会在写入中加载,然后当它到达 stdout.read() 时,它会运行该行,然后停止。 Not sure exactly what is going on and how I can get the output of the calls.不知道到底发生了什么以及如何获得呼叫的 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()

Try:尝试:

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.

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