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!
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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With