I'm currently using Thonny to write and execute my Python scripts in, and would like to be able to exit a loop by me pressing a key or button somewhere, so I can terminate the script graciously (run some cleaning-up code).
Does Thonny offer any such thing (apart from its way-too-crude "stop" button I mean) ?
If not, is there any other way ? Directly reading the keyboard directly requires root, and I've not seen any kind of non-blocking(!) "OK" message boxes.
On Mon, 16 Dec 2019 12:48:43 +0100, "R.Wieser" declaimed the following:
Let's back up a bit...
How would you "terminate the script graciously (run some cleaning-up code)" if you ran your script from the command line/shell?
Most IDEs run scripts by spawning a process and connecting stdin/stdout to that process (so they can pass keystrokes to the process and capture output for display in some console window of the IDE).
I suspect that "stop" button is the equivalent of sending a to the running process -- just like you'd do in a command line/shell.
The most common would be to wrap your script in an exception handler, trapping KeyboardInterrupt """ exception KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. The exception inherits from BaseException so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting. """
try: all your code except KeyboardInterrupt: cleanup code sys.exit()
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
Under DOS/Windows ? By checking if a certain key was being pressed, and if so exit the loop, allowing the (cleanup) code following the loop to be executed. But as this is Linux I haven't got the foggiest.
I know. That is why I specifically mentioned Thonny. It could be pushing the keystrokes into the stdin of the Python program, but have no idea if it actually does that.
If I would not have found something that uses that very key combination to enable me to exit a loop I would most likely have agreed with you. :-)
The code in the below traps SIGINT, which seems to be generated by pressing ctrl-c. Thonny's "stop" button does not get trapped by it.
formatting link
I had that in some example code downloaded, and I could not get the script to terminate that way. But as I wanted to make absolutily sure I just now tried some minimal code. And ofcourse /now/ it works. :-\
ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here.
All logos and trade names are the property of their respective owners.