当 运行 在子进程库中使用 popen 或 运行 时,如何在 python 中单独打印输入提示?

How can I print an input prompt in python on its own line when ran using popen or run in the subprocess library?

我创建了以下示例来说明我的问题:

假设 student_file.py 是:

curr_year = int(input("Enter year: "))
print(f"Next year is {curr_year + 1}")

所以当 运行 运行程序时,终端中的输出如下:

Enter year: 4323
Next year is 4324

在我的例子中,我运行正在使用这个学生文件使用多个输入的另一个程序,因此所需的输出如下所示:

Enter year: 
Next year is 3234
Enter year: 
Next year is 3112
Enter year: 
Next year is 1322
Enter year: 
Next year is 2222

但是,对于当前代码片段,例如 temp.py:

from subprocess import Popen, PIPE
year_list = ['3233\n', '3111\n', '1321\n', '2221']
for year in year_list:
    p = Popen(["python3", "student_file.py"], stdout=PIPE, stdin=PIPE, encoding="ascii")
    output = p.communicate(input=year)[0]
    print(output, end="")

当前输出为:

Enter year: Next year is 3234
Enter year: Next year is 3112
Enter year: Next year is 1322
Enter year: Next year is 2222

因为我在测试其他文件,根本不想改student_file.py,只想修改test.py。这可能吗?我可以使用任何方法来完成此操作,无论是 popen、运行 还是其他方法,只要它能实现所需的输出即可。

谢谢。

只是一点解决方法:)

from subprocess import Popen, PIPE
year_list = ['3233\n', '3111\n', '1321\n', '2221']
for year in year_list:
    p = Popen(["python3", "student_file.py"], stdout=PIPE, stdin=PIPE, encoding="ascii")
    output = p.communicate(input=year)[0]
    print(output.replace(": ",": \n"), end="")

使用 Pexpect

import pexpect
year_list = ['3233', '3111', '1321', '2221']
for year in year_list:
    child = pexpect.spawn("python student_file.py")

    child.sendline(year)
    lines = [i.decode('utf-8').rstrip() for i in child.readlines()]
    for line in lines:
        print(line)
``