我创建了以下示例来说明我的问题:
比方说,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,run还是其他方法,我都可以使用任何方法来完成。
谢谢。
只是一些解决方法:)
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="")