Making sure a Python script with subprocesses dies on SIGINT

前端 未结 5 867
感动是毒
感动是毒 2020-12-29 18:36

I\'ve got a command that I\'m wrapping in script and spawning from a Python script using subprocess.Popen. I\'m trying to make sure it dies if the

5条回答
  •  隐瞒了意图╮
    2020-12-29 19:11

    I found a -e switch in the script man page:

    -e      Return the exit code of the child process. Uses the same format
             as bash termination on signal termination exit code is 128+n.
    

    Not too sure what the 128+n is all about but it seems to return 130 for ctrl-c. So modifying your cmd to be

    cmd = [ 'script', '-e', '-q', '-c', "sleep 2 && (exit 1)", '/dev/null']
    

    and putting

    if p.returncode == 130:
        break
    

    at the end of the for loop seems to do what you want.

提交回复
热议问题