繁体   English   中英

当使用 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}")

所以运行程序时,终端中的output是这样的:

Enter year: 4323
Next year is 4324

在我的情况下,我正在运行另一个使用这个学生文件使用多个输入的程序,因此所需的 output 看起来像:

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="")

output 目前是:

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、run 还是其他方法,只要它完成了所需的 output。

谢谢你。

只是一个小解决方法:)

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)
``

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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