exception KeyboardInterrupt and os.system command

Donn Cave donn at u.washington.edu
Mon Nov 28 19:21:25 CET 2005


In article <1133168674.088374.142790 at z14g2000cwz.googlegroups.com>,
 "malv" <malvert at telenet.be> wrote:
> That's also kind of what I expected.
> However, I quickly tried:
> import os
> while 1:
>      y = os.system("sleep 1")
>      z = (y >> 8) & 0xFF
>      print z
> 
> I never get anything in return but 0, hitting c-C or not.
> I have uset the above code to get exit code returns in the past though.
> Would there be anything special with sleep?

That algorithm will give you the same thing as os.WEXITSTATUS(),
on most platforms, though not necessarily all so it's better
to use the function.

On platforms where it works, exit status is of course stored in
2nd byte from the low end, and signal status is stored separately,
in the low byte.  So naturally, your right shift discards the
signal status and you're left with 0.

On the other hand, if you use os.spawnv, signal status will
be returned as a negative integer, instead of a positive
integer exit status.  spawnv() is safer than system() if the
command is constructed from data, and it also doesn't block
SIGINT in the caller like system does, so it would work for
the problem posed in the original post.

But it might be just as well to watch the process status for
any non-zero value, and then call the graceful exit procedure.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list