gpt4 book ai didi

python - 子进程 readline 挂起等待 EOF

转载 作者:行者123 更新时间:2023-11-28 23:04:11 52 4
gpt4 key购买 nike

我有一个简单的 C++ 程序,我试图通过 Python 脚本执行它。 (我是编写脚本的新手)并且无法通过管道读取输出。据我所见,如果没有 EOF,readline() 似乎将无法工作,但我希望能够在程序中间读取并让脚本响应正在输出的内容。它没有读取输出,而是挂起python 脚本:

#!/usr/bin/env python
import subprocess
def call_random_number():
print "Running the random guesser"
rng = subprocess.Popen("./randomNumber", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
i = 50
rng.stdin.write("%d\n" % i)
output = rng.stdout.readline()
output = rng.stdout.readline()

call_random_number()

和 c++ 文件,它生成 1 到 100 之间的随机数,然后检查用户的猜测,直到他们猜对为止

#include<iostream>
#include<cstdlib>

int main(){
std::cout<< "This program generates a random number from 1 to 100 and asks the user to enter guesses until they succuessfully guess the number. It then tells the user how many guesses it took them\n";
std::srand(std::time(NULL));
int num = std::rand() % 100;
int guessCount = 0;
int guess = -1;
std::cout << "Please enter a number: ";
std::cin >> guess;
while(guess != num){
if (guess > num){
std::cout << "That guess is too high. Please guess again: ";
} else {
std::cout << "That guess is too low. Please guess again: ";
}
std::cin >> guess;
guessCount++;
}
std::cout << "Congratulations! You solved it in " << guessCount << " guesses!\n";
}

最终目标是让脚本通过二进制搜索解决问题,但现在我只想能够读取一行而不是文件末尾

最佳答案

作为@Ron Reiter pointed out ,您不能使用 readline() 因为 cout 不会隐式打印换行符——您需要 std::endl“\n” 在这里。

对于交互式使用,当您无法更改子程序时,pexpect module提供了几种方便的方法(通常是 it solves for free: input/output directly from/to terminal (outside of stdin/stdout) and block-buffering issues ):

#!/usr/bin/env python
import sys

if sys.version_info[:1] < (3,):
from pexpect import spawn, EOF # $ pip install pexpect
else:
from pexpect import spawnu as spawn, EOF # Python 3

child = spawn("./randomNumber") # run command
child.delaybeforesend = 0
child.logfile_read = sys.stdout # print child output to stdout for debugging
child.expect("enter a number: ") # read the first prompt
lo, hi = 0, 100
while lo <= hi:
mid = (lo + hi) // 2
child.sendline(str(mid)) # send number
index = child.expect([": ", EOF]) # read prompt
if index == 0: # got prompt
prompt = child.before
if "too high" in prompt:
hi = mid - 1 # guess > num
elif "too low" in prompt:
lo = mid + 1 # guess < num
elif index == 1: # EOF
assert "Congratulations" in child.before
child.close()
break
else:
print('not found')
child.terminate()
sys.exit(-child.signalstatus if child.signalstatus else child.exitstatus)

它有效,但它是二分查找因此 (traditionally) there could be bugs .

下面是一段使用subprocess模块进行比较的类似代码:

#!/usr/bin/env python
from __future__ import print_function
import sys
from subprocess import Popen, PIPE

p = Popen("./randomNumber", stdin=PIPE, stdout=PIPE,
bufsize=1, # line-buffering
universal_newlines=True) # enable text mode
p.stdout.readline() # discard welcome message: "This program gener...

readchar = lambda: p.stdout.read(1)
def read_until(char):
buf = []
for c in iter(readchar, char):
if not c: # EOF
break
buf.append(c)
else: # no EOF
buf.append(char)
return ''.join(buf).strip()

prompt = read_until(':') # read 1st prompt
lo, hi = 0, 100
while lo <= hi:
mid = (lo + hi) // 2
print(prompt, mid)
print(mid, file=p.stdin) # send number
prompt = read_until(':') # read prompt
if "Congratulations" in prompt:
print(prompt)
print(mid)
break # found
elif "too high" in prompt:
hi = mid - 1 # guess > num
elif "too low" in prompt:
lo = mid + 1 # guess < num
else:
print('not found')
p.kill()
for pipe in [p.stdin, p.stdout]:
try:
pipe.close()
except OSError:
pass
sys.exit(p.wait())

关于python - 子进程 readline 挂起等待 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897202/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com