簡體   English   中英

如何使用 python 子進程從標准輸出中獲取 output?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM