Search code examples
pythonsubprocesspopen

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


I've created the following example to illustrate my question:

Let's say student_file.py is:

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

So when running the program, the output in the terminal is like:

Enter year: 4323
Next year is 4324

In my case, I'm running another program that uses multiple inputs using this student file, so the desired output looks like:

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

However, with the current code snippet in, for example, 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="")

The output is currently:

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

Because I'm testing other files, I don't want to change student_file.py at all, and only want to modify test.py. Is this possible at all? I'm fine with using any method to accomplish this, whether it be popen, run, or something else as long as it accomplishes this desired output.

Thank you.


Solution

  • Just a little Workaround :)

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

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