skibum
Posts: 16
Joined: Fri Jan 27, 2017 1:45 pm

ctrl-c in python (the ^C being displayed specifically)

Sun Nov 17, 2019 1:12 pm

Ok, I'm sure I'm missing something obvious here.

In the simplest form I've a program that does :-

Code: Select all

try:
    print("\n Hello")
    input(" Pause ... ")
except KeyboardInterrupt:
    pass
Not rocket science.

When you run it, it waits until you press ctrl-c and exits. All good. But it also displays the '^C' on the screen.

Code: Select all

pi@pi4-2:~ $ python3 test.py

 Hello
 Pause ... ^Cpi@pi4-2:~ $
I'm looking for a simple way to stop the "^C" being displayed on the screen.

Thanks

pcmanbob
Posts: 10159
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: ctrl-c in python (the ^C being displayed specifically)

Sun Nov 17, 2019 1:52 pm

You could try this

https://linux.m2osw.com/remove-ctrl-C-f ... in-console

just be careful not to break your ~/.bashrc file
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

danjperron
Posts: 3526
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: ctrl-c in python (the ^C being displayed specifically)

Sun Nov 17, 2019 1:58 pm

A simple method will be to backspace to remove the ^C

Code: Select all

try:
    print("\n Hello")
    input(" Pause ... ")
except KeyboardInterrupt:
    print(chr(8)+chr(8),end="") 

skibum
Posts: 16
Joined: Fri Jan 27, 2017 1:45 pm

Re: ctrl-c in python (the ^C being displayed specifically)

Sun Nov 17, 2019 2:02 pm

pcmanbob wrote:
Sun Nov 17, 2019 1:52 pm
You could try this

https://linux.m2osw.com/remove-ctrl-C-f ... in-console

just be careful not to break your ~/.bashrc file
Thanks for that. Went with controlling the stty in python. With the following if anyone is interested :-

Code: Select all

import termios, sys
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~ termios.ECHOCTL
termios.tcsetattr(fd, termios.TCSADRAIN, new)

try:
    print("\n Hello")
    input(" Pause ... ")
except KeyboardInterrupt:
    termios.tcsetattr(fd, termios.TCSADRAIN, old)
    pass

Paul Hutch
Posts: 562
Joined: Fri Aug 25, 2017 2:58 pm
Location: Blackstone River Valley, MA, USA
Contact: Website

Re: ctrl-c in python (the ^C being displayed specifically)

Sun Nov 17, 2019 3:58 pm

I don't see the Ctrl+C's when I quit my programs but instead of a pass for keyboard interrupts I have:

Code: Select all

    except KeyboardInterrupt:
        sys.exit(0)

Return to “Python”