1

I've searched this topic to no avail for hours.

Is it possible to do something along the lines of:

try:
    input_var = input('> ')
except KeyboardInterrupt:
    print("This will not work.")

But when I try this and do CTRL-C, it just does nothing.

Is there any other way to achieve this?

Using Windows 10, Python 3.5.2, and Powershell

Note: I am not using the input_var for printing, I am doing 3 if/elif/else statements based around it.

Aaron
  • 445
  • 1
  • 4
  • 11

1 Answers1

2

It sounds like you would be interested in the signal module.

This Answer demonstrates how to use the signal module to capture Ctrl+C, or SIGINT.

For your use case, something along the lines of the following would work :

#!/usr/local/bin/python3
import signal

def signal_handler(signal, frame):
    raise KeyboardInterrupt('SIGINT received')

signal.signal(signal.SIGINT, signal_handler)
try :
    input_var = input('> ')
except KeyboardInterrupt :
    print("CTRL+C Pressed!")
Community
  • 1
  • 1
arbo
  • 21
  • 2
  • Just tried it, it just returned this: Traceback (most recent call last): – Aaron Jul 29 '16 at 01:10
  • Looks like your comment was cut off; this works for me using python3. Keep in mind that if run using python2, raw_input() should be used in place of input() – arbo Jul 29 '16 at 01:45
  • I modified the answer to use python3 by default, I didn't catch that at the time of writing. You'll need to change the first line to match your python install location, or run the script as > python3 script.py – arbo Jul 29 '16 at 01:50
  • Im doing it exactly as you have said, still not doing a single thing... – Aaron Jul 29 '16 at 01:55
  • I already said. "Traceback (most recent call last): " its not getting cut off... It's not even an error. – Aaron Jul 29 '16 at 02:15
  • Curious... Sadly I can't reproduce this on Windows / Powershell as I'm working on linux, but I'll do some digging. – arbo Jul 29 '16 at 02:22