How to interrupt Python subprocesses on Windows when using Python C API?

我只是一个虾纸丫 提交于 2019-12-06 12:17:59

That's how I finally got the console allocated without flashing console window (thanks to @eryksun for the pointers):

import sys
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

cmd = [sys.executable, "-c", "print('Hi!'); input()"]
child = subprocess.Popen(cmd,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)

child.stdout.readline() # now I know subprocess is ready
result = kernel32.AttachConsole(child.pid)
if not result:
    err = ctypes.get_last_error()
    print("Could not allocate console. Error code:", err, file=sys.stderr)
child.stdin.write(b"\n") # allow subprocess to complete
child.stdin.flush()

Basically I stole the console from a dummy subprocess.

I'll propose one possible solution according to @eryksun's comment.

Just do

import ctypes
ctypes.windll.kernel32.AllocConsole() 

in parent process.

Unfortunately (as eryksun also noted), this also creates unnecessary and confusing console window.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!