Skip to content
Advertisement

CTRL+C not handled in python script when using su

I have a Python code like this.

try:
    while some_cond_is_still_true:
        ....
except KeyboardInterrupt: # Handle CTRL+C
    ...

While the KeyboardInterrupt is handled fine if I run the python script by myself, it is not handled if I run it as another user using su, like this.

su <some_other_user> -c 'python myprogram.py <args>'

How can I solve this problem?

Advertisement

Answer

The su command creates a new interactive shell and executes the command inside it. When you use option -c (--command) the su command creates a new session with the user indicated in the command. To solve this use the option --session-command. In this case the command will be this:

su user_name --session-command 'python myprogram.py <args>'

in this case you should be able to catch CTRL+C interrupt.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement