0

I need to read a single char from stdin and then unread it so that the next time an input method is called, that char should be included in the result. In C++, cin.putback does this. What is the equivalent in Python?

Please note that I don't need to intermingle different input methods/functions.

Abhishek Kumar
  • 298
  • 4
  • 10
  • Possible duplicate of [How can I simulate input to stdin for pyunit?](http://stackoverflow.com/questions/6271947/how-can-i-simulate-input-to-stdin-for-pyunit) – Torxed Jan 20 '17 at 12:00

3 Answers3

2

In Python 3, sys.stdin has a property called buffer that is an instance of io.BufferedReader and so has a peek method. This should allow you to do sys.stdin.buffer.peek(1)[:1], which would let you look at the next character in standard input without reading (consuming) it.

wildwilhelm
  • 4,809
  • 1
  • 19
  • 24
0

There isn't a simple analogue in Python.

Your best bet is probably to read the characters into an list in your program, and then later consume them from that list.

Katriel
  • 120,462
  • 19
  • 136
  • 170
0

I found a Python module called CIn which does exactly what I want. It is available on GitHub: https://github.com/abhishekkr200802/CIn

Abhishek Kumar
  • 298
  • 4
  • 10