Python: How to prevent subprocesses from receiving CTRL-C / Control-C / SIGINT

前端 未结 5 806
有刺的猬
有刺的猬 2020-12-13 00:26

I am currently working on a wrapper for a dedicated server running in the shell. The wrapper spawns the server process via subprocess and observes and reacts to its output.<

5条回答
  •  北海茫月
    2020-12-13 00:49

    you can do something like this to make it work in windows and unix:

    import subprocess
    import sys
    
    def pre_exec():
        # To ignore CTRL+C signal in the new process
        signal.signal(signal.SIGINT, signal.SIG_IGN)
    
    if sys.platform.startswith('win'):
        #https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
        #CREATE_NEW_PROCESS_GROUP=0x00000200 -> If this flag is specified, CTRL+C signals will be disabled
        my_sub_process=subprocess.Popen(["executable"], creationflags=0x00000200)
    else:
        my_sub_process=subprocess.Popen(["executable"], preexec_fn = pre_exec)
    

提交回复
热议问题