How to use string as stdin

I'm going crazy about a simple Python question: I want to call a function that uses raw_input () and input () and somehow supply them with a string in my program. I searched and found that the subprocess can change stdin and stdout to PIPE; however, I cannot use a subprocess to call a function. Here is 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.

Thank you so much!

+6
python
source share
1 answer

Temporarily replace sys.stdin with 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!' 
+10
source share

All Articles