Issue
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.
Solution
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:
- Open a CMD window
- Start IPython by running
ipython kernel
. It should print something like
cmd> 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
- Open Spyder and connect to the IPython kernel using "Consoles > Connect to an existing kernel". This will open a dialog asking for a connection file.
- Click the "Browse" button on the far right and select "kernel-3436.json" (the same name that IPython printed when it was started it).
- If code such as
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.
Answered By - hengin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.