8

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

5
  • Pass the value to the function as a parameter? It kind of depends on what you're doing with it. Commented Oct 16, 2017 at 17:36
  • Just have the function return the value you would have manually entered and skip the call to input Commented Oct 16, 2017 at 17:37
  • I just edited it to specify that I can't change the internals of the function. It works how it works Commented Oct 16, 2017 at 17:38
  • 2
    Put the text in a file and invoke the script redirecting the input from that file. Commented Oct 16, 2017 at 17:38
  • Was about to say the same as @kindall . that's the easiest way to go about it keeping the function same. Commented Oct 16, 2017 at 17:40

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

4

I highly, highly suggest you implement a context manager, and strictly use this context manager whenver you want to do this. So, something like:

import sys

class as_stdin:
    def __init__(self, buffer):
        self.buffer = buffer
        self.original_stdin = sys.stdin
    def __enter__(self):
        sys.stdin = self.buffer
    def __exit__(self, *exc):
        sys.stdin = self.original_stdin

Then you can redirect your stdin in a much more tightly controlled way:

>>> import io
>>> from redirect import as_stdin
>>> def echo():
...     print(input())
...
>>> with as_stdin(io.StringIO('hello, world')):
...     echo()
...
hello, world
>>> x = input()
hello, x
>>>
>>> print(x)
hello, x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.