如何使用 StringIO() 对象作为程序的标准输入来将字符串发送到输入语句,

How to use a StringIO() object as the program's stdin to send a string to an input statement,

我希望能够将程序的标准输入重新路由到 StringIO() 对象,以便我可以模拟用户对输入语句的响应。

newstdin = StringIO()
sys.stdin = newstdin
newstdin.write("hey")
newstdin.seek(0)

response = input()
print(response)

当响应已经在 StringIO() 对象中时,我的代码可以工作,但是如果什么都没有,它会立即引发 EOF 错误,而不是像设置为正常时那样等待响应 sys.stdin.我怎样才能做到这一点,以便 input() 语句等待将响应写入 StringIO() 对象(这将在单独的线程中完成)。谢谢!

如果有人感兴趣,我决定这样做的方式是:

accinput = input

def input(prompt=None):
    if prompt:
        print(prompt)
    while True:
        try:
            return accinput()
        except EOFError:
            pass

您可以将输入的实际功能存储在 accinput 中,重新定义输入以不断重试从标准输入 stringIO() 读取输入,直到它不满足 EOFError.