killing a script
steve+comp.lang.python at pearwood.info
Tue Aug 30 06:13:41 CEST 2011
On Tue, 30 Aug 2011 08:53 am Arnaud Delobelle wrote:
>> Yes, but if I am not mistaken, that will require me to put a line or
>> two after each os.system call. That's almost like whack-a-mole at the
>> code level rather than the Control-C level. OK, not a huge deal for
>> one script, but I was hoping for something simpler. I was hoping I
>> could put one line at the top of the script and be done with it.
> Write a function! That's what they're for after all :)
I'm not sure that this is actually as simple as that, especially using
As I understand it, the scenario is this:
The main script looks something like this:
for x in whatever:
Each time through the loop, a new Python process is started. Each process
runs in the foreground, capturing standard input, and so hitting Ctrl-C
kills *that* process, not the main script. Unless, by chance, the Ctrl-C
happens after the system call returns, but before the next one starts, it
is completely invisible to the parent process (the main script). Wrapping
os.system in a function does nothing to fix that.
Possibly using the subprocess module may help.
Otherwise, the only way around this I can think of is to ensure that
the 'something.py' script (or scripts!) each return an error code for "User
for x in whatever:
result = os.system('something.py x')
if result == 3: # User Cancelled
But if the 'something.py' scripts are arbitrary scripts, I don't think you
have any easy way around it. Perhaps use threads, and have the main script
ask the thread to kill the child process?
Regardless, this is a hard problem, and it isn't possible to just have some
magic switch at the top of your script to make it work. You actually have
to do the work yourself.
(But of course you can do the work inside a function, and re-use it
More information about the Python-list