You can do it by temporarily changing stdin
which is where the input()
function gets its data:
from contextlib import contextmanagerfrom io import StringIOimport sys@contextmanagerdef redirect_stdin(source): save_stdin = sys.stdin sys.stdin = StringIO('\n'.join(source)+'\n') yield sys.stdin = save_stdindef example_function(): a = input() b = input() print(a+b) c = input() d = input() print(c+d) returninp = ['a', 'b', 'c', 'd']with redirect_stdin(inp): example_function()
Output:
abcd