Reputation: 343
Has anyone come across a way to emulate kbhit()
in the Spyder environment on Windows? Somehow the development environment gets between the Python program and the keyboard, so any simple way of doing it (i.e. msvcrt.kbhit()
) does not work.
Upvotes: 2
Views: 776
Reputation: 36
The reason that msvcrt does not work in Spyder is that the iPython console is embedded in a Qt widget (source code here) which handles keyboard input very differently than the CMD console.
Mehdi's answer above is the most practical way to get around it. However, it is also possible to connect Spyder to an external IPython console that runs inside a CMD terminal:
ipython kernel
. It should print something likecmd> ipython kernel
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
To exit, you will have to explicitly quit this process, by either sending
"quit" from a client, or using Ctrl-\ in UNIX-like environments.
To read more about this, see https://github.com/ipython/ipython/issues/2049
To connect another client to this kernel, use:
--existing kernel-3436.json
import msvcrt
print('Press a key!')
key = msvcrt.getch()
print('You pressed:', key)
is run from Spyder, the output will appear in Spyder's IPython terminal. But to provide input, you have to set focus to the CMD window.
It is even possible to run a debugger, but support for doing so with an external kernel seems very limited. There is no GUI integration. Instead PDB commands must be entered directly into the Spyder IPython terminal. According to this issue from 2013, that is unlikely to change.
Upvotes: 2
Reputation: 753
Set this configuration in Spyder:
Run > Run Configuration Per File > Execute In An External System Terminal
In my experience "msvcrt.kbhit" only works in CMD.
Upvotes: 2