簡體   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