A:我在windows下面使用subprocess打开了一个进程,请问如何在程序里面关闭它?
代码:
import subproces
process = subprocess.Popen(['python.exe','-c','while 1: pass'])
Q:我们可以使用pywin32或者ctypes调用windows API来完成关闭它的任务。可以通过Popen对象的_handle或者pid来关闭进程,
方法1:
import win32api
win32api.TerminateProcess(int(process._handle), -1)
方法2:
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)
方法3:
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
方法4:
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)