Sending ^C to Python subprocess objects on Windows

前端 未结 6 1227
离开以前
离开以前 2020-12-07 19:06

I have a test harness (written in Python) that needs to shut down the program under test (written in C) by sending it ^C. On Unix,

proc.send_sign         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 19:46

    My solution also involves a wrapper script, but it does not need IPC, so it is far simpler to use.

    The wrapper script first detaches itself from any existing console, then attach to the target console, then files the Ctrl-C event.

    import ctypes
    import sys
    
    kernel = ctypes.windll.kernel32
    
    pid = int(sys.argv[1])
    kernel.FreeConsole()
    kernel.AttachConsole(pid)
    kernel.SetConsoleCtrlHandler(None, 1)
    kernel.GenerateConsoleCtrlEvent(0, 0)
    sys.exit(0)
    

    The initial process must be launched in a separate console so that the Ctrl-C event will not leak. Example

    p = subprocess.Popen(['some_command'], creationflags=subprocess.CREATE_NEW_CONSOLE)
    
    # Do something else
    
    subprocess.check_call([sys.executable, 'ctrl_c.py', str(p.pid)]) # Send Ctrl-C
    

    where I named the wrapper script as ctrl_c.py.

提交回复
热议问题