Python win32api.CloseHandle() Examples
The following are 30
code examples of win32api.CloseHandle().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
win32api
, or try the search function
.
Example #1
Source File: handles.py From ironpython2 with Apache License 2.0 | 6 votes |
def testCleanup1(self): # We used to clobber all outstanding exceptions. def f1(invalidate): import win32event h = win32event.CreateEvent(None, 0, 0, None) if invalidate: win32api.CloseHandle(int(h)) 1/0 # If we invalidated, then the object destruction code will attempt # to close an invalid handle. We don't wan't an exception in # this case def f2(invalidate): """ This function should throw an IOError. """ try: f1(invalidate) except ZeroDivisionError, exc: raise IOError("raise 2")
Example #2
Source File: ABuWinUtil.py From abu with GNU General Public License v3.0 | 6 votes |
def socket_bind_recv(socket_fn, cmd_handler): """ 非bsd系统的进程间通信,接受消息,处理消息,使用windows全局共享内存实现, 函数名称保持与bsd的接口名称一致 :param socket_fn: 共享内存文件名称 :param cmd_handler: cmd处理函数,callable类型 """ if not callable(cmd_handler): print('socket_bind_recv cmd_handler must callable!') while True: global_fn = 'Global\\{}'.format(socket_fn) event = w32e.CreateEvent(None, 0, 0, global_fn) event_mmap = mmf.mmapfile(None, socket_fn, 1024) w32e.WaitForSingleObject(event, -1) socket_cmd = event_mmap.read(1024).decode() # 把接收到的socket传递给外部对应的处理函数 cmd_handler(socket_cmd) event_mmap.close() win_api.CloseHandle(event)
Example #3
Source File: file.py From peach with Mozilla Public License 2.0 | 6 votes |
def genProcesses(self): CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: print(sys.stderr, "Failed getting first process.") return while True: yield pe32 if Process32Next(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: break CloseHandle(hProcessSnap)
Example #4
Source File: BackgroundProcess.py From p2ptv-pi with MIT License | 6 votes |
def send_startup_event(): if sys.platform == 'win32': try: import win32event import win32api except: return try: if DEBUG: log('bg::send_startup_event') startupEvent = win32event.CreateEvent(None, 0, 0, 'startupEvent') win32event.SetEvent(startupEvent) win32api.CloseHandle(startupEvent) if DEBUG: log('bg::send_startup_event: done') except: log_exc()
Example #5
Source File: process.py From peach with Mozilla Public License 2.0 | 6 votes |
def genProcesses(self): CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot Process32First = ctypes.windll.kernel32.Process32First Process32Next = ctypes.windll.kernel32.Process32Next CloseHandle = ctypes.windll.kernel32.CloseHandle hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) pe32 = PROCESSENTRY32() pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) if Process32First(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: print("Failed getting first process.") return while True: yield pe32 if Process32Next(hProcessSnap, ctypes.byref(pe32)) == win32con.FALSE: break CloseHandle(hProcessSnap)
Example #6
Source File: process.py From peach with Mozilla Public License 2.0 | 6 votes |
def closeApp(self, hProcess, title): """ Close Application by window title """ try: win32gui.EnumWindows(FileWriterLauncherGui.enumCallback, title) if proc is not None: win32event.WaitForSingleObject(hProcess, 5 * 1000) win32api.CloseHandle(hProcess) for pid in self.genChildProcesses(proc): try: handle = win32api.OpenProcess(1, False, pid) win32process.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass except: pass
Example #7
Source File: process.py From peach with Mozilla Public License 2.0 | 6 votes |
def closeApp(self, hProcess, title): """ Close Application by window title """ try: win32gui.EnumWindows(FileWriterLauncherGui.enumCallback, title) if hProcess is not None: win32event.WaitForSingleObject(hProcess, 5 * 1000) win32api.CloseHandle(hProcess) for pid in self.genChildProcesses(proc): try: handle = win32api.OpenProcess(1, False, pid) win32process.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass except: pass
Example #8
Source File: debugger.py From peach with Mozilla Public License 2.0 | 5 votes |
def GetProcessIdByName(procname): """ Try and get pid for a process by name. """ ourPid = -1 procname = procname.lower() try: ourPid = win32api.GetCurrentProcessId() except: pass pids = win32process.EnumProcesses() for pid in pids: if ourPid == pid: continue try: hPid = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid) try: mids = win32process.EnumProcessModules(hPid) for mid in mids: name = str(win32process.GetModuleFileNameEx(hPid, mid)) if name.lower().find(procname) != -1: return pid finally: win32api.CloseHandle(hPid) except: pass return None
Example #9
Source File: ABuWinUtil.py From abu with GNU General Public License v3.0 | 5 votes |
def socket_send_msg(socket_fn, msg): """ 非bsd系统的进程间通信,发送消息,使用windows全局共享内存实现,函数名称保持与bsd的接口名称一致 :param socket_fn: : 共享内存名称 :param msg: 字符串类型需要传递的数据,不需要encode,内部进行encode """ global_fn = 'Global\\{}'.format(socket_fn) event = w32e.OpenEvent(w32e.EVENT_ALL_ACCESS, 0, global_fn) event_mmap = mmf.mmapfile(None, socket_fn, 1024) w32e.SetEvent(event) event_mmap.write(msg) event_mmap.close() win_api.CloseHandle(event)
Example #10
Source File: inject-dll.py From WpadEscape with GNU General Public License v3.0 | 5 votes |
def close_handle(handle): return win32api.CloseHandle(handle)
Example #11
Source File: _pollingfile.py From python-for-android with Apache License 2.0 | 5 votes |
def close(self): try: win32api.CloseHandle(self.pipe) except pywintypes.error: # You can't close std handles...? pass
Example #12
Source File: _pollingfile.py From python-for-android with Apache License 2.0 | 5 votes |
def writeConnectionLost(self): self.deactivate() try: win32api.CloseHandle(self.writePipe) except pywintypes.error: # OMG what pass self.lostCallback()
Example #13
Source File: IPC.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def stop(self): if self.master: r = win32event.WaitForSingleObject(self.mutex, win32event.INFINITE) filename = self._get_sic_path() try: os.remove(filename) except OSError, e: # print, but continue traceback.print_exc() self.master = 0 win32event.ReleaseMutex(self.mutex) # close it so the named mutex goes away win32api.CloseHandle(self.mutex) self.mutex = None
Example #14
Source File: pykill.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def kill_process(name): for pid in win32process.EnumProcesses(): # do try not to kill yourself if pid == win32api.GetCurrentProcessId(): continue try: p = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ | win32con.PROCESS_TERMINATE, False, pid) except: continue if not p: continue try: hl = win32process.EnumProcessModules(p) except: win32api.CloseHandle(p) continue h = hl[0] pname = win32process.GetModuleFileNameEx(p, h) root, pname = os.path.split(pname) #print name, pname if compare(name, pname): #print "KILL", pname win32api.TerminateProcess(p, 0) win32api.CloseHandle(p) return True win32api.CloseHandle(p) return False
Example #15
Source File: process.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def _closeStdin(self): if hasattr(self, "hChildStdinWr"): win32file.CloseHandle(self.hChildStdinWr) del self.hChildStdinWr self.closingStdin = False self.closedStdin = True
Example #16
Source File: process.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def closeStderr(self): if hasattr(self, "hChildStderrRd"): win32file.CloseHandle(self.hChildStderrRd) del self.hChildStderrRd self.closedStderr = True self.connectionLostNotify()
Example #17
Source File: process.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def closeStdout(self): if hasattr(self, "hChildStdoutRd"): win32file.CloseHandle(self.hChildStdoutRd) del self.hChildStdoutRd self.closedStdout = True self.connectionLostNotify()
Example #18
Source File: _pollingfile.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def writeConnectionLost(self): self.deactivate() try: win32api.CloseHandle(self.writePipe) except pywintypes.error: # OMG what pass self.lostCallback()
Example #19
Source File: winguiauto.py From pyAutoTrading with GNU General Public License v2.0 | 5 votes |
def _readListViewItems(hwnd, column_index=0): # Allocate virtual memory inside target process pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(win32con.PROCESS_ALL_ACCESS, False, struct.unpack("i", pid)[0]) pLVI = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, win32con.MEM_RESERVE | win32con.MEM_COMMIT, win32con.PAGE_READWRITE) # Prepare an LVITEM record and write it to target process memory lvitem_str = struct.pack('iiiiiiiii', *[0, 0, column_index, 0, 0, pBuffer, 4096, 0, 0]) lvitem_buffer = ctypes.create_string_buffer(lvitem_str) copied = ctypes.create_string_buffer(4) p_copied = ctypes.addressof(copied) WriteProcessMemory(hProcHnd, pLVI, ctypes.addressof(lvitem_buffer), ctypes.sizeof(lvitem_buffer), p_copied) # iterate items in the SysListView32 control num_items = win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMCOUNT) item_texts = [] for item_index in range(num_items): win32gui.SendMessage(hwnd, commctrl.LVM_GETITEMTEXT, item_index, pLVI) target_buff = ctypes.create_string_buffer(4096) ReadProcessMemory(hProcHnd, pBuffer, ctypes.addressof(target_buff), 4096, p_copied) item_texts.append(target_buff.value) VirtualFreeEx(hProcHnd, pBuffer, 0, win32con.MEM_RELEASE) VirtualFreeEx(hProcHnd, pLVI, 0, win32con.MEM_RELEASE) win32api.CloseHandle(hProcHnd) return item_texts
Example #20
Source File: RDP.py From XFLTReaT with MIT License | 5 votes |
def cleanup(self): try: common.internal_print("Shutting down module: RDP Dynamic Virtual Channel") common.internal_print("Please exit XFLTReaT...") win32api.CloseHandle(self.comms_socket) except Exception as e: pass if self.serverorclient: self.packetselector.delete_client(self.client)
Example #21
Source File: windows_support.py From avocado-vt with GNU General Public License v2.0 | 5 votes |
def __del__(self): win32api.CloseHandle(self._read_ovrlpd.hEvent) win32api.CloseHandle(self._write_ovrlpd.hEvent)
Example #22
Source File: handles.py From ironpython2 with Apache License 2.0 | 5 votes |
def testCleanup2(self): # Cause an exception during object destruction. # The worst this does is cause an ".XXX undetected error (why=3)" # So avoiding that is the goal import win32event h = win32event.CreateEvent(None, 0, 0, None) # Close the handle underneath the object. win32api.CloseHandle(int(h)) # Object destructor runs with the implicit close failing h = None
Example #23
Source File: handles.py From ironpython2 with Apache License 2.0 | 5 votes |
def testCleanup3(self): # And again with a class - no __del__ import win32event class Test: def __init__(self): self.h = win32event.CreateEvent(None, 0, 0, None) win32api.CloseHandle(int(self.h)) t=Test() t = None
Example #24
Source File: handles.py From ironpython2 with Apache License 2.0 | 5 votes |
def testCleanupGood(self): # And check that normal error semantics *do* work. import win32event h = win32event.CreateEvent(None, 0, 0, None) win32api.CloseHandle(int(h)) self.assertRaises(win32api.error, h.Close) # A following Close is documented as working h.Close()
Example #25
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def _getInvalidHandleException(self): try: win32api.CloseHandle(1) except win32api.error, exc: return exc
Example #26
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testFuncIndex(self): exc = self._getInvalidHandleException() self._testExceptionIndex(exc, 1, "CloseHandle")
Example #27
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testUnpack(self): try: win32api.CloseHandle(1) self.fail("expected exception!") except win32api.error, exc: self.failUnlessEqual(exc.winerror, winerror.ERROR_INVALID_HANDLE) self.failUnlessEqual(exc.funcname, "CloseHandle") expected_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() self.failUnlessEqual(exc.strerror, expected_msg)
Example #28
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testAsStr(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must always look like one err_tuple = (winerror.ERROR_INVALID_HANDLE, 'CloseHandle', err_msg) self.failUnlessEqual(str(exc), str(err_tuple))
Example #29
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testAsTuple(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() # early on the result actually *was* a tuple - it must be able to be one err_tuple = (winerror.ERROR_INVALID_HANDLE, 'CloseHandle', err_msg) if sys.version_info < (3,): self.failUnlessEqual(tuple(exc), err_tuple) else: self.failUnlessEqual(exc.args, err_tuple)
Example #30
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def testAttributes(self): exc = self._getInvalidHandleException() err_msg = win32api.FormatMessage(winerror.ERROR_INVALID_HANDLE).rstrip() self.failUnlessEqual(exc.winerror, winerror.ERROR_INVALID_HANDLE) self.failUnlessEqual(exc.strerror, err_msg) self.failUnlessEqual(exc.funcname, 'CloseHandle') # some tests for 'insane' args.