Sending ^C to Python subprocess objects on Windows

前端 未结 6 1220
离开以前
离开以前 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:57

    Here is a fully working example which doesn't need any modification in the target script.

    This overrides the sitecustomize module so it might no be suitable for every scenario. However, in this case you could use a *.pth file in site-packages to execute code at the subprocess startup (see https://nedbatchelder.com/blog/201001/running_code_at_python_startup.html).

    Edit This works only out of the box for subprocesses in Python. Other processes have to manually call SetConsoleCtrlHandler(NULL, FALSE).

    main.py

    import os
    import signal
    import subprocess
    import sys
    import time
    
    
    def main():
        env = os.environ.copy()
        env['PYTHONPATH'] = '%s%s%s' % ('custom-site', os.pathsep,
                                        env.get('PYTHONPATH', ''))
        proc = subprocess.Popen(
            [sys.executable, 'sub.py'],
            env=env,
            creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
            )
        time.sleep(1)
        proc.send_signal(signal.CTRL_C_EVENT)
        proc.wait()
    
    
    if __name__ == '__main__':
        main()
    

    custom-site\sitecustomize.py

    import ctypes
    import sys
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    
    if not kernel32.SetConsoleCtrlHandler(None, False):
        print('SetConsoleCtrlHandler Error: ', ctypes.get_last_error(),
              file=sys.stderr)
    

    sub.py

    import atexit
    import time
    
    
    def cleanup():
        print ('cleanup')
    
    atexit.register(cleanup)
    
    
    while True:
        time.sleep(1)
    

提交回复
热议问题