Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a string as stdin

Tags:

python

I have been going crazy over a seemingly easy question with Python: I want to call a function that uses raw_input() and input(), and somehow supply those with a string in my program. I've been searching and found that subprocess can change stdin and stdout to PIPE; however, I can't use subprocess to call a function. Here's an example:

def test():
    a = raw_input("Type something: ")
    return a

if __name__=='__main__':
    string = "Hello World" # I want to a in test() to be Hello World
    returnValue = test()

Of course this is much simpler than what I'm trying to accomplish, but the basic idea is very similar.

Thanks a lot!

like image 268
dangmai Avatar asked Feb 21 '11 06:02

dangmai


1 Answers

Temporarily replace sys.stdin with a StringIO or cStringIO with the desired string.

>>> s = StringIO.StringIO('Hello, world!')
>>> sys.stdin = s ; r = raw_input('What you say?\n') ; sys.stdin = sys.__stdin__ 
What you say?
>>> r
'Hello, world!'
like image 121
Ignacio Vazquez-Abrams Avatar answered Oct 19 '22 06:10

Ignacio Vazquez-Abrams