Quantcast
Channel: User martineau - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by martineau for Pass a list to a function instead of user-input - Jupiter

$
0
0

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

Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>