Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set an "input" in a Python function automatically?

So in case the above question doesn't make any sense, I have a function in Python (not written by me but I have to run it many times) that requires the use of the "input" function. I.e.

def foo():
    x = input()
    ~~Do stuff~~
    return ~~some relevant variable~~

But I don't want to have to type in the input every single time. What is the best way to "automatically" enter an input such that I don't have to continually input the values?

Important Edit: Its very important to note that I cannot change the function. The thing must be entered as an STDIN input

like image 708
wjmccann Avatar asked Oct 16 '17 17:10

wjmccann


1 Answers

You can change the standard input by a string stream or a file by doing something similar to this:

import sys
from io import StringIO

sys.stdin = StringIO('test')

Then each call to input() will get the value on the string stream.

EDIT: You can then read a file and update the value of sys.stdin each time with a value per line.

like image 133
Martin Alonso Avatar answered Sep 18 '22 22:09

Martin Alonso