If the program is one you are writing, the best way to do this is to capture signals from the operating system and specify in the program how you want the program to handle them. Then, you can use the (unfortunately named IMO) kill command to send the appropriate signal to the program so that it stops in the manner you want. (Unfortunately, I have never done this with Python, but it looks like you may be able to use os.kill to send the signal.) Of course, you could do the same thing if it's not a program you wrote, but you know (or find out, possibly by trial and error) that it handles a specific signal in a fashion you desire.
I don't have Ubuntu, but you may be able to get a list of signals available by typing man signal at the command line.