Search code examples
pythonstdinpython-2.x

How to assign a specific value to sys.stdin?


I'm using the following code:

#!/usr/bin/env python

import sys
from io import StringIO

#data = sys.stdin.readlines()
sys.stdin = """
hello I feel good
how are you?
where have you been?
"""
for line in sys.stdin:
    print line

When i run the above code, the print line prints out each character of the texts assigned to sys.stdin. It prints one character per line:

h
e
l
l
o

I

....truncated

I'm trying to get the output to be as it was stored in sys.stdin, it should look like this:

hello I feel good
how are you?
where have you been?

Solution

  • This seems to work:

    from io import StringIO
    import sys
    
    data = u"""\
    hello I feel good
    how are you?
    where have you been?
    """
    
    sys.stdin = StringIO(data)
    
    for line in sys.stdin:
        print line.rstrip()
    

    Output:

    hello I feel good
    how are you?
    where have you been?