Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a value to interactive input in a passive way in Python?

Tags:

python

input

I use a function that gets some input from the user interactively and returns some values. I'd like to run the function (without changing it) without having to type in the values myself, e.g. have it read from a list. How can I achieve this?

MCVE:

def add():
    a = int(input('first number: '))
    b = int(input('first number: '))
    return(a+b)

And I want to be able to run something like magic(add(), [2, 3]) to get the output 5.

like image 665
kmi Avatar asked Nov 27 '25 10:11

kmi


2 Answers

Assuming you are on Linux or wsl, you can just pipe some input through stdin. I.e.,

$ echo $'1\n3\n' | python scripy.py

should produce 4. If you have a file with the same contents, you can do the same using cat

$ cat file.in | python script.py

only if absolutely necessary:

python can also be used to simulate stdin. sys.stdin is simply an instance of the StringIO class. We can override the default sys.stdin with a StringIO class with contents of our choice.

with StringIO(in_string) as f:
    tmp = sys.stdin
    sys.stdin = f
    add()
    sys.stdin = tmp
like image 198
xzkxyz Avatar answered Nov 29 '25 00:11

xzkxyz


One option is to make a test where you mock out input:

from unittest.mock import patch

@patch("builtins.input")
def test_add(mock_input):
    input_values = [2, 3]
    mock_input.side_effect = input_values
    expected_value = sum(input_values)
    actual_value = add()
    # print or log actual value here if you want to see the result
    assert actual_value == expected_value

this is quite a round about way if you are trying to automate the use of some third party function that annoyingly uses input, but if you're just trying to test their function, its not bad.

like image 20
Dan Avatar answered Nov 29 '25 00:11

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!