Dependent on the operating system and the libraries available, there are different ways of achieving that. This answer provides a few of them.
Here is the Linux/OS X part copied from there, with in infinite loop terminated using the escape character. For the Windows solution you can check the answer itself.
import sys
import select
import tty
import termios
from curses import ascii
def isData():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
old_settings = termios.tcgetattr(sys.stdin)
try:
tty.setcbreak(sys.stdin.fileno())
i = 0
while 1:
print i
i += 1
if isData():
c = sys.stdin.read(1)
if c == ascii.ESC:
break
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
Edit: Changed the character detection to use characters as defined by curses.ascii
, thanks to Daenyth's unhappiness with magic values which I share.