r/pythonhelp • • Jan 14 '22

Script that Automatically provides input() in terminal.

File A is designed to automate a process and has a for loop that calls file B.

File B has an input() function, and when it it called it halts the for loop until a user input is provided.

Is there a way where I can automatically fill the input within the terminal?

(Note: I am unable to alter file B)

3 Upvotes

10 comments sorted by

2

u/Goobyalus Jan 14 '22

b.py:

def f():
    for i in range(10):
        print(input(f"{i}: "))

a.py:

import b
from unittest.mock import patch


def alternate_input(prompt, *args, **kwargs):
    print(prompt, end='')
    return "x"


with patch('builtins.input', alternate_input):
    b.f()

Output:

0: x
1: x
2: x
3: x
4: x
5: x
6: x
7: x
8: x
9: x

2

u/Muskratbest2 Jan 14 '22

Thank you for your reply, When I say input i mean the actual function that requires a user input in the terminal:

input(‘OptionalPrompt’)

1

u/Goobyalus Jan 14 '22

Above shows module a calling a function from module b. We patched the builtin input function to be the function we defined, alternate_input, instead. So when b.f calls input, it is actually calling alternate_input.

Isn't that what you're asking? If not, I don't understand.

Can you show exactly what you mean by "File A ... calls file B?"

1

u/Muskratbest2 Jan 14 '22 edited Jan 14 '22

FILE A:

import os

os.system(“B.py”)

FILE B:

input = input(“Input: “)

print(“Here’s the input: “ + input)

1

u/Goobyalus Jan 14 '22

How is file A calling file B here?

And you can format code on reddit by leaving blank spaces before and after the code block, and indendint each line of the code block be an additional 4 spaces.

1

u/Muskratbest2 Jan 14 '22

My apologies, did this fix the formatting?

1

u/Goobyalus Jan 14 '22

Not really, but I see now that the os.system changed from A to B.

Do you need to run B with os.system, or can you import B?

1

u/Muskratbest2 Jan 14 '22

I believe that I do need to run with os.system, yes

Also yes my apologies that was a typo

1

u/Goobyalus Jan 14 '22

os.system doesn't give you control over the environment of the subprocess.


With the subprocess module, you could take control over stdin, stdout, and stderr and communicate with the subprocess that way, writing into stdin from A's process to B's process as though A were a user in the terminal.


Using os.system or subprocess to run one python script from another is probably a mistake.

1

u/Muskratbest2 Jan 14 '22

Okay thank you for your help!