Search code examples
pythoninputiosysstringio

How to use a StringIO() object as the program's stdin to send a string to an input statement,


I would like be able to reroute the stdin of my program to a StringIO() object so that I can simulate user response to an input statement.

newstdin = StringIO()
sys.stdin = newstdin
newstdin.write("hey")
newstdin.seek(0)

response = input()
print(response)

My code works when a response is already in the StringIO() object however if there isn't anything, it immediately raises a EOF error instead of waiting for a response like it would if set to the normal sys.stdin. How can I do this so that the input() statement waits for a response to be written to the StringIO() object (this will be done in a separate thread). Thanks!


Solution

  • If anyone is interested, the way I have decided to do it is with this:

    accinput = input
    
    def input(prompt=None):
        if prompt:
            print(prompt)
        while True:
            try:
                return accinput()
            except EOFError:
                pass
    

    You can store the real functionality of input in accinput the redefine input to continuously retry to read input from the stdin stringIO() until it doesn't meet an EOFError.