def __del__( self ): #disconnect the instrument if it goes outof scope even if no explicit command is given 'disconnect the instrument if it goes outof scope even if no explicit command is given' if self.__class__.__sDevicedict[self.key] != None: if not self.disconnected: _warn("Instrument instance of %s Not disconnected explicitly" % self.pid) time.sleep(5) self.disconnect() if dbg: print "disconnected..." self.__class__.__sCounter[self.key] -= 1 if not self.__class__.__sCounter[self.key]: print "Destroying Mutex :", self.key debug(DestroyMutex=self.key) win32api.CloseHandle(self.__class__.__sMutex[self.key]) del self.__class__.__sDevicedict[self.key]
def processTerminate(uPid): """ The Windows version of base.processTerminate """ fRc = False try: hProcess = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, uPid) except: reporter.logXcpt('uPid=%s' % (uPid, )) else: try: win32process.TerminateProcess(hProcess, 0x40010004) # DBG_TERMINATE_PROCESS fRc = True except: reporter.logXcpt('uPid=%s' % (uPid, )) win32api.CloseHandle(hProcess) return fRc
def tearDown(self): global WEBDRIVER_PROCESS self.driver.quit() if WEBDRIVER_PROCESS: if sys.version_info < (2,6): # From http://stackoverflow.com/questions/1064335 if platform.system() == 'Windows': PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, WEBDRIVER_PROCESS.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) else: os.kill(WEBDRIVER_PROCESS.pid, signal.SIGKILL) else: WEBDRIVER_PROCESS.kill() WEBDRIVER_PROCESS = None
def close(self): """Close all associated file objects and handles.""" #log.debug("[%s] _FileWrapper.close()", id(self)) if not self.mClosed: self.mClosed = True if self._file is not None: #log.debug("[%s] _FileWrapper.close: close file", id(self)) self._file.close() #log.debug("[%s] _FileWrapper.close: done file close", id(self)) if self._handle is not None: #log.debug("[%s] _FileWrapper.close: close handle", id(self)) try: win32api.CloseHandle(self._handle) except win32api.error: #log.debug("[%s] _FileWrapper.close: closing handle raised", # id(self)) pass
def KillNameServer(self): c = wmi.WMI() pID = self.c_Pid ps = len(c.Win32_Process(ProcessId=pID)) while (ps == 1): ps = len(c.Win32_Process(ProcessId=pID)) sleep(2) PROCESS_TERMINATE = 1 for pid in self.pids: try: handle = win32api.OpenProcess(PROCESS_TERMINATE, False, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except: pass
def is_process_active(pid): """ @param pid long @return bool """ ret = False try: h = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid) if h: status = win32process.GetExitCodeProcess(h) ret = status == win32con.STILL_ACTIVE win32api.CloseHandle(h) except: pass #except Exception, e: dwarn(e) return ret
def main(): # set C locale, otherwise python and wxpython complain locale.setlocale(locale.LC_ALL, 'C') # get the directory of our exetutable file # when running as pyexe built module currentDir = Utils.GetCurrentDir(True) os.chdir(currentDir) Utils.CreateProfile() # see if we are already running and exit if so try: # try to acquire our active mutex hMutex = win32event.OpenMutex(win32con.SYNCHRONIZE, False, MainWindow.ACTIVE_MUTEX) # could open it - most likely another window is active # just to be sure wait for it to see if it is claimed if win32event.WaitForSingleObject(hMutex, 0) == win32event.WAIT_TIMEOUT: # mutex is claimed, another window is already running - terminate return win32api.CloseHandle(hMutex) except win32api.error: pass conf_file = None for arg in sys.argv[1:]: if arg.find('--config_file=') == 0: conf_file = Utils.SafeExpandEnvironmentStrings( arg[len('--config_file='):]) if conf_file is None: conf_file = os.path.join(Utils.GetProfileDir(True), 'ClamWin.conf') if not os.path.isfile(conf_file): conf_file = 'ClamWin.conf' config = Config.Settings(conf_file) config.Read() logon = False for arg in sys.argv[1:]: if arg == '--logon': logon = True w = MainWindow(config, logon) win32gui.PumpMessages()
def pid_exists(pid): """ check if the given pid number is an currently running process """ LOG = LogHelper.get_app_logger(logging.INFO) if pid != None and pid == "android": # android serialization workaround return True if sys.platform[:3] == "win": # check if process exists hProc = None try: hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, int(pid)) except Exception: LOG.info("exception while quering") return False finally: if hProc != None: # close handle the process exist LOG.info("process exists %s handle ", pid) win32api.CloseHandle(hProc) return True else: LOG.info("process failed to get handle") return False try: # the second parameter is the signal code # If sig is 0, then no signal is sent, but error checking is still performed. # if "os.kill" throws no exception, the process exists os.kill(int(pid), 0) # if no exception is thrown kill the current process return True except OSError, e: # the process with the provided pid does not exist enymore # so an exception is thrown # ESRCH means "no such process" print errno.ESRCH if e.errno == errno.ESRCH: return False else: raise
def kill_processes(process_name): if sys.platform != 'win32': raise NotImplementedError('Implement me!') try: import win32api import win32pdhutil import win32con except ImportError: log.warn('Python win32 is required for killing processes.') return pids = win32pdhutil.FindPerformanceAttributesByName( process_name, counter="ID Process") for pid in pids: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle)
def die_with_parent(): ppid = get_ppid() if not ppid: return try: hpproc = win32api.OpenProcess(win32con.SYNCHRONIZE, False, ppid) if not hpproc: return # waiting parent process win32event.WaitForSingleObject(hpproc, win32event.INFINITE) # kill myself win32api.TerminateProcess(win32api.GetCurrentProcess(), 0) finally: if hpproc: win32api.CloseHandle(hpproc)
def terminate(self): """终止进程 """ #2011/01/27 pear 在终止进程前,使该进程在系统托盘中的图标销毁 from tuia.wincontrols import TrayNotifyBar self._adjustProcessPrivileges() try: hProcess = win32api.OpenProcess(win32con.PROCESS_TERMINATE, False, self._pid).Detach() win32process.TerminateProcess(hProcess, 0) win32api.CloseHandle(hProcess) tb = TrayNotifyBar() item = tb[self._pid] if item: item.destroy() except: pass
def stop(self): ''' Change state such that send/receave will not work. For Tcp this could be closing a connection, for a file it might be closing the file handle. ''' if self.hDevice == None: return buff = "STOP!" bytesReturned = 0 win32file.DeviceIoControl(self.hDevice, self.IOCTL_PEACH_METHOD_STOP, buff, 1) win32api.CloseHandle(self.hDevice) self.hDevice = None
def main(): parser = argparse.ArgumentParser() parser.add_argument('pipe_name', type=str) args = parser.parse_args() _Initialize() try: SocketServer.TCPServer.allow_reuse_address = True server_address = ('127.0.0.1', 0) server = SocketServer.TCPServer(server_address, MsrRequestHandler) handle = win32file.CreateFile(args.pipe_name, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) _, port = server.server_address win32file.WriteFile(handle, str(port)) win32api.CloseHandle(handle) server.serve_forever() finally: _Deinitialize()
def runProcessesCycle(): for (exeName, processId) in getProcessList(): if not exeName.lower() in MONITORED_PROCESSES: continue handle = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, 0, processId) if not handle: continue userTimeSec = win32process.GetProcessTimes( handle)['UserTime'] / 10000000 if userTimeSec > USER_TIME_THRESHOLD_SEC: print '%s Killing process %s, pid=%s userTimeSec=%s' % ( time.ctime(), exeName, processId, userTimeSec) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle)
def find_spotify_uwp(hwnd, windows): text = win32gui.GetWindowText(hwnd) classname = win32gui.GetClassName(hwnd) if classname == "Chrome_WidgetWin_0" and len(text) > 0: # Retrieve the thread id and process id that created the Spotify window _, proc_id = win32process.GetWindowThreadProcessId(hwnd) # Retrieve a handle to the Spotify process proc_h = win32api.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, proc_id) # Get the file path of the Spotify process path = win32process.GetModuleFileNameEx(proc_h, None) # Close the handle win32api.CloseHandle(proc_h) if Path(path).name == "Spotify.exe": windows.append(text) # Stop enumeration once we found it # This will always throw a pywintypes.error by design return False
def subprocess_terminate(proc): try: proc.terminate() except AttributeError: print " no terminate method to Popen.." try: import signal os.kill(proc.pid, signal.SIGTERM) except AttributeError: print " no os.kill, using win32api.." try: import win32api PROCESS_TERMINATE = 1 handle = win32api.OpenProcess(PROCESS_TERMINATE, False, proc.pid) win32api.TerminateProcess(handle, -1) win32api.CloseHandle(handle) except ImportError: print " ERROR: could not terminate process."
def close_excel_by_force(excel): try: # Get the window's process id's hwnd = excel.Hwnd t, p = win32process.GetWindowThreadProcessId(hwnd) # Ask window nicely to close win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) # Allow some time for app to close time.sleep(10) # If the application didn't close, force close except Exception as e: pass try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p) if handle: win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) except Exception as e: pass
def kill(self): """ Try to close and kill the application Dialogs may pop up asking to save data - but the application will be killed anyway - you will not be able to click the buttons. This should only be used when it is OK to kill the process like you would do in task manager. """ windows = self.windows(visible_only=True) for win in windows: try: if hasattr(win, 'close'): win.close() continue except TimeoutError: self.actions.log('Failed to close top level window') if hasattr(win, 'force_close'): self.actions.log('application.kill: call win.force_close') win.force_close() try: process_wait_handle = win32api.OpenProcess( win32con.SYNCHRONIZE | win32con.PROCESS_TERMINATE, 0, self.process) except win32gui.error: return True # already closed # so we have either closed the windows - or the app is hung killed = True if process_wait_handle: try: win32api.TerminateProcess(process_wait_handle, 0) except win32gui.error: self.actions.log('Process {0} seems already killed'.format(self.process)) win32api.CloseHandle(process_wait_handle) return killed
def _launch_worker(self, wait=False): worker = Worker(self._push_server_address, self._pull_server_address, self._ipc_authkey, self._callback_launcher) worker.start() if sys.platform == 'win32': permissions = win32con.PROCESS_TERMINATE | win32con.PROCESS_SET_QUOTA handle = win32api.OpenProcess(permissions, False, worker.pid) try: win32job.AssignProcessToJobObject(self._job_obj, handle) finally: win32api.CloseHandle(handle) if wait: worker.wait_start() self.workers.append(worker) return worker
def kill_process(pid): """Kills a process with the given id""" try: handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid) #JOSH: intarwebs says this: #handle = win32api.OpenProcess(True, win32con.PROCESS_TERMINATE, pid) #win32api.TerminateProcess(handle,-1) if handle: win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle) except Exception, e: #this basically means that the process died while we were trying to kill it, which is fine if hasattr(e, "args") and len(e.args) > 1 and e.args[ 0] == 5 and e.args[1] == "TerminateProcess": return if hasattr(e, "args") and len( e.args) > 1 and e.args[0] == 87 and e.args[1] == "OpenProcess": return raise e
def _DestroyOldSlaveProcesses(self): """Check for and kill any existing gears slave processes. Gears internal tests create some slave processes while running. Here we check to see if any did not shut down properly and destroy any that remain. """ if not wmi: return process_list = wmi.WMI().Win32_Process(Name='rundll32.exe') for process in process_list: pid = process.ProcessID print 'RUNDLL32 PROCESS** %s' % process.CommandLine if process.CommandLine.rfind('gears.dll') > 0: print 'Killing deadlocked slave process: %d' % pid handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid) win32api.TerminateProcess(handle, 0) win32api.CloseHandle(handle)
def getItems(hwnd): from split_image import export_image tbs = get_table_maps() dstpath = "d:\\outico3" os.makedirs(dstpath, exist_ok = True) im = Image.open('E:\\02.resource\\ico\\gptico\\GPTMap_179.bmp') pid = ctypes.create_string_buffer(4) p_pid = ctypes.addressof(pid) GetWindowThreadProcessId(hwnd, p_pid) # process owning the given hwnd hProcHnd = OpenProcess(PROCESS_ALL_ACCESS, False, struct.unpack("i",pid)[0]) pTVI = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE) pBuffer = VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE) # iterate items in the SysListView32 control hRoot = win32gui.SendMessage(hwnd, TVM_GETNEXTITEM, TVGN_CHILD, TVI_ROOT) hChild = win32gui.SendMessage(hwnd, TVM_GETNEXTITEM, TVGN_CHILD, hRoot) while hChild: itxt, istate, iimage = get_item_info(hwnd, hProcHnd, pTVI, pBuffer, hChild) print(itxt, istate) try: fn = itxt[:itxt.index('(')] if fn.startswith('井斜'): fn = '井轨迹' if fn.startswith('测井'): fn = '测井曲线' except: fn = itxt fn = tbs.get(fn) if fn: fn = os.path.join(dstpath, 'data-'+fn) export_image(im, iimage*16, fn) if istate!=0: export_image(im, (iimage+1)*16, fn+'-expand') hChild = win32gui.SendMessage(hwnd, TVM_GETNEXTITEM, TVGN_NEXT, hChild) VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE) VirtualFreeEx(hProcHnd, pTVI, 0, MEM_RELEASE) win32api.CloseHandle(hProcHnd)
def _launch_flexlogger(cls, timeout_in_seconds: float, path: Optional[Path] = None) -> int: import win32api # type: ignore import win32event # type: ignore if path is not None and not path.name.lower().endswith(".exe"): path = path / _FLEXLOGGER_EXE_NAME if path is None: path = cls._get_latest_installed_flexlogger_path() if path is None: raise RuntimeError( "Could not determine latest installed path of FlexLogger") event_name = uuid.uuid4().hex mapped_name = uuid.uuid4().hex event = win32event.CreateEvent(None, 0, 0, event_name) args = [str(path)] args += [ "-mappedFileIsReadyEventName=" + event_name, "-mappedFileName=" + mapped_name, ] args += ["-enableAutomationServer"] try: subprocess.Popen(args) timeout_end_time = time.time() + timeout_in_seconds while True: # Only wait for 200 ms at a time so we can still be responsive to Ctrl-C object_signaled = win32event.WaitForSingleObject(event, 200) if object_signaled == 0: return cls._read_int_from_mmap(mapped_name) elif object_signaled != win32event.WAIT_TIMEOUT: raise RuntimeError( "Internal error waiting for FlexLogger to launch. Error code %d" % object_signaled) if time.time() >= timeout_end_time: raise RuntimeError( "Timed out waiting for FlexLogger to launch. This might mean an " "instance of FlexLogger was already running.") finally: win32api.CloseHandle(event)
def main(argv): # Determine what action, w.r.t. mozilla.exe, this komodo.exe should take: # KA_NOTHING: Komodo (mozilla.exe) is running already, nothing to do. # KA_WAIT: Komodo is currently starting up. Just wait for it to start # up and then proceed. # KA_STARTANDWAIT: There is no Komodo running or starting. Start Komodo # and wait for it to startup. KA_NOTHING, KA_WAIT, KA_STARTANDWAIT = range(3) lock = acquireKomodoStatusLock() status = getKomodoStatus() startingHandle = None if status == KS_NOTRUNNING: action = KA_STARTANDWAIT startingHandle = setKomodoStatusToStarting() elif status == KS_STARTING: action = KA_WAIT elif status == KS_RUNNING: action = KA_NOTHING else: raise "Unexpected Komodo status: %r" % status releaseKomodoStatusLock(lock) # Perform the appropriate action. After this Komodo is up and running. if action == KA_NOTHING: pass elif action == KA_STARTANDWAIT: startMozilla() if not waitUntilKomodoIsRunning(): print "XXX wait was not successful, starting mozilla again" startMozilla() waitUntilKomodoIsRunning() elif action == KA_WAIT: if not waitUntilKomodoIsRunning(): startMozilla() waitUntilKomodoIsRunning() else: raise "Unexpected action for komodo.exe: %r" % action if startingHandle and sys.platform.startswith("win"): win32api.CloseHandle(startingHandle) cmds = ["open\t%s\n" % os.path.abspath(arg) for arg in argv[1:]] issueKomodoCommandments(cmds)
def GetStatistics(self): retstr = '' rights = win32con.PROCESS_ALL_ACCESS #totalPeak = 0 #totalWorking = 0 handle = None try: handle = None handle = win32api.OpenProcess(rights, 0, self.PID) memory = win32process.GetProcessMemoryInfo(handle) retstr += '\n' + GetLineDivider() retstr += 'Process Name : %10s\n' % self.Name retstr += 'Process ID : %10d\n' % self.PID index = 0 for i in list(memory.keys()): if memory[i] < 0: memory[i] = 0 if index < 2: retstr += '%-30s: %10u\n' % (i, memory[i]) else: retstr += '%-30s: %10u KB\n' % (i, memory[i] / 1024) index = index + 1 #totalPeak = totalPeak + ( memory["PeakWorkingSetSize"] / 1024 ) #totalWorking = totalWorking + ( memory["WorkingSetSize"] / 1024 ) except Exception as inst: if len(inst.args) == 3: number = inst.args[0] function = inst.args[1] message = inst.args[2] retstr += 'ERROR %#08x (%s): %s\n' % (number, function, message) else: retstr += str(inst) + '\n' finally: if handle: win32api.CloseHandle(handle) return retstr + '\n' + GetLineDivider()
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)
def process_exists(pid): try: if USE_PROCESS_QUERY_LIMITED_INFORMATION: #this one potentially works even for other user's processes h = win32api.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) else: h = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, 0, pid) except pywintypes.error as e: if e.winerror == winerror.ERROR_INVALID_PARAMETER: #This error is returned if the pid doesn't match any known process return False elif e.winerror == winerror.ERROR_ACCESS_DENIED: raise AccessDeniedError(e) #Other errors are not expected raise try: exitcode = win32process.GetExitCodeProcess(h) return exitcode == win32con.STILL_ACTIVE finally: win32api.CloseHandle(h)
def listProcessModules(pid): ''' 32位进程不能枚举64位进程 ''' hprocess = None modules = [] try: hprocess = win32api.OpenProcess( win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ | win32con.PROCESS_ALL_ACCESS, False, pid) moduleinfo = win32process.EnumProcessModules(hprocess) for module in moduleinfo: modulefile = win32process.GetModuleFileNameEx(hprocess, module) modules.append(modulefile) return modules except: return modules finally: if hprocess: win32api.CloseHandle(hprocess)
def __init__(self): # enable required SeSystemEnvironmentPrivilege privilege privilege = win32security.LookupPrivilegeValue( None, 'SeSystemEnvironmentPrivilege' ) token = win32security.OpenProcessToken( win32process.GetCurrentProcess(), win32security.TOKEN_READ|win32security.TOKEN_ADJUST_PRIVILEGES ) win32security.AdjustTokenPrivileges( token, False, [(privilege, win32security.SE_PRIVILEGE_ENABLED)] ) win32api.CloseHandle( token ) # get windows firmware variable API try: self._GetFirmwareEnvironmentVariable = kernel32.GetFirmwareEnvironmentVariableW self._GetFirmwareEnvironmentVariable.restype = c_int self._GetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] self._SetFirmwareEnvironmentVariable = kernel32.SetFirmwareEnvironmentVariableW self._SetFirmwareEnvironmentVariable.restype = c_int self._SetFirmwareEnvironmentVariable.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int] self._SetFirmwareEnvironmentVariableEx = kernel32.SetFirmwareEnvironmentVariableExW self._SetFirmwareEnvironmentVariableEx.restype = c_int self._SetFirmwareEnvironmentVariableEx.argtypes = [c_wchar_p, c_wchar_p, c_void_p, c_int, c_int] except AttributeError: logging.warn( "Some get/set functions don't't seem to exist" )
def pid_running(pid): """Return True if we know if process with pid is currently running, False if it isn't running, and None if we don't know for sure.""" if os.name == 'nt': import win32api import win32con import pywintypes process = None try: process = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, 0, pid) except pywintypes.error as error: if error.winerror == 87: # parameter incorrect, PID does not exist return False elif error.winerror == 5: # access denied, means nevertheless PID still exists return True else: log.Log( "Unable to check if process ID {pi} " "is still running".format(pi=pid), log.WARNING) return None # we don't know if the process is running else: if process: win32api.CloseHandle(process) return True else: return False else: try: os.kill(pid, 0) except ProcessLookupError: # errno.ESRCH - pid doesn't exist return False except OSError: # any other OS error log.Log( "Unable to check if process ID {pi} " "is still running".format(pi=pid), log.WARNING) return None # we don't know if the process is still running else: # the process still exists return True