1

I have a shell script which I am using to call many python scripts. I've added a trap in my shell script to catch ctrl+c and exit. But if a python script is running and I hit ctrl+c, it also shows the block of the python script that was being executed! I do not want that. I know the better way would be to add KeyboardInterrupt in my python scripts, but that will take a lot of effort. I want a solution such that when I hit ctrl+c, te control the script execution ends silently.

for eg: a.sh:

   control_c() {
    echo
    echo 'Keyboard Interrupt'
    exit
}
trap control_c INT
python b.py

b.py:

from time import sleep
sleep(50)

when I run a.sh and I hit ctrl+c, I do not want to see the python block like this:

^CTraceback (most recent call last):
  File "b.py", line 3, in <module>
    sleep(50)
KeyboardInterrupt

Keyboard Interrupt

I want it to exit with a simple 'Keyboard Interrupt' message.

Jolta
  • 2,620
  • 1
  • 29
  • 42

2 Answers2

1

I'm not sure this is a good practice, but if you need it just wrapp your sleep in a try / except statement.

try:
    sleep(50)
except KeyboardInterrupt:
    pass

Edit because of OP comment:

You can do a Python wrapper which catch KeyboardInterrupt, it's pretty dirty, but you can do something like:

import imp
try:
    imp.load_source('module.name', '/path/to/script.py')
except KeyboardInterrupt:
    exit()

Because your python file (/path/to/script.py) is not a lib but a script it will be executed when loaded, so you can catch errors one layer upper and so do it in more generic way. You surely will have to deal with others issues I think, but i should do the work.

You can check this question for more about imp and how to load python libs.

Community
  • 1
  • 1
Arount
  • 9,853
  • 1
  • 30
  • 43
0

You can simply place your standard out to /dev/null

#!/usr/bin/env bash

control_c() {
    echo
    echo "Keyboard Interrupt"
    exit
}

trap control_c INT
python b.py 2>/dev/null
NinjaGaiden
  • 3,046
  • 6
  • 28
  • 49
  • I can do it but I do not want to suppress the whole output. I just want to suppress the error block in case of trap. – Shikhar Awasthi Nov 28 '16 at 14:16
  • When you say "whole output" do you mean standard output or standard error? The current script will suppress all standard error and print Keyboard Interrupt as standard out because of trap. – NinjaGaiden Nov 28 '16 at 14:20
  • Both. If an error occurs, I want to display it. When the file executes correctly, I want to display the output. But when I give ctrl+c, I want it to silently exit! – Shikhar Awasthi Nov 28 '16 at 14:22