3

This is for console (command line) python applications that have no GUI framework. I expect I should be able to write a script in python and run it on Windows, Mac and Linux, and have it have a loop which can be exited by pressing Escape. However implementing such a script or console/commandline tool in python is non trivial.

The canonical example of keyboard hit detection on python are typically:

  • Linux only giant blobs of code involving termios

  • A single platform only sample (curses, or win32 api, or mac apis), import msvcrt, for example.

Surely something as GENERAL as detecting (without waiting for input) the press of a key (such as escape key, to abort a loop in a script), that is part of Python's built in modules or built in functions, that works out of the box on mac, linux and windows.

I have searched for such a thing and cannot find it. I am not looking for help locating a third party library as I only want a solution that is suitable for scripts shared among various machines that should ideally be self contained and not rely on anything that does not come installed out of the box on some default install of python 3.5 or higher.

Note that if I only wanted to catch control-C I could use this technique.

Surely we've moved the ball forward from the ugly and non-portable hacks we had available in 2008.

Community
  • 1
  • 1
Warren P
  • 65,725
  • 40
  • 181
  • 316
  • Well, since it quite obviously does not exist, you should perhaps question your assumptions: something like this is **very far** from "GENERAL". In fact it is a highly specific requirement which depends not only on the platform but what you're doing within that platform. – Daniel Roseman Jul 28 '16 at 14:08
  • Hmm. The thing which I think is GENERAL is that a console script might do some repeated action and then be able to accept a keyboard hit (ESC, or something else) and abort. Something other than Ctrl-C. Imagine the tool is like a ping tool, and has a command line flag to run until interrupted. If curses ran on windows, for example, I'd be all set but it does not. I have seen implementations that try to import msvcrt and then try to import curses and maybe then termios, but this seems so ugly to me for some reason. – Warren P Jul 28 '16 at 14:40

0 Answers0