Search code examples
pythonpython-3.xstdin

Write function result to stdin


I'm trying to write the results of a function to stdin.

This is the code :

def testy():
    return 'Testy !'

import sys
sys.stdin.write(testy())

And the error I get is :

Traceback (most recent call last):
  File "stdin_test2.py", line 7, in <module>
    sys.stdin.write(testy())
io.UnsupportedOperation: not writable

I'm not completely sure, is this the right way of doing things ?


Solution

  • You could mock stdin with a file-like object?

    import sys
    import StringIO
    
    oldstdin = sys.stdin
    sys.stdin = StringIO.StringIO('asdlkj')
    
    print raw_input('.')       #  .asdlkj