我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.WinError()。
def hide_file(path): """ Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text. """ __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD SetFileAttributes.restype = ctypes.wintypes.BOOL FILE_ATTRIBUTE_HIDDEN = 0x02 ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN) if not ret: raise ctypes.WinError()
def getvolumeinfo(path): """ Return information for the volume containing the given path. This is going to be a pair containing (file system, file system flags). """ # Add 1 for a trailing backslash if necessary, and 1 for the terminating # null character. volpath = ctypes.create_unicode_buffer(len(path) + 2) rv = GetVolumePathName(path, volpath, len(volpath)) if rv == 0: raise WinError() fsnamebuf = ctypes.create_unicode_buffer(MAX_PATH + 1) fsflags = DWORD(0) rv = GetVolumeInformation(volpath, None, 0, None, None, byref(fsflags), fsnamebuf, len(fsnamebuf)) if rv == 0: raise WinError() return (fsnamebuf.value, fsflags.value)
def _get_terminal_size(fd): handle = windll.kernel32.GetStdHandle(_handle_ids[fd]) if handle == 0: raise OSError('handle cannot be retrieved') if handle == -1: raise WinError() csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) if res: res = struct.unpack("hhhhHhhhhhh", csbi.raw) left, top, right, bottom = res[5:9] columns = right - left + 1 lines = bottom - top + 1 return terminal_size(columns, lines) else: raise WinError()
def get_windows_env_var(key): """Get an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) buf = ctypes.create_unicode_buffer(32767) stored = winapi.GetEnvironmentVariableW(key, buf, 32767) if stored == 0: raise ctypes.WinError() return buf[:stored]
def set_windows_env_var(key, value): """Set an env var. Raises: WindowsError """ if not isinstance(key, text_type): raise TypeError("%r not of type %r" % (key, text_type)) if not isinstance(value, text_type): raise TypeError("%r not of type %r" % (value, text_type)) status = winapi.SetEnvironmentVariableW(key, value) if status == 0: raise ctypes.WinError()
def shell__register_window_hook(hwnd, message_id_callbacks=None, callback=None): """ Registers the "shell hook" window message with the window, and inserts the callback into the message_id_callbacks dict for processing, because the message ID is dynamically created. :param hwnd: :param message_id_callbacks: :param callback: :return: the message ID for the shell hook message. """ assert message_id_callbacks is None or isinstance(message_id_callbacks, dict) if not RegisterShellHookWindow(hwnd): raise WinError() message_id = RegisterWindowMessageW("SHELLHOOK") if message_id_callbacks: message_id_callbacks[message_id] = callback return message_id
def process__get_exit_code(thread_pid): """ :param thread_pid: :return: None if the process hasn't exited, or the int exit code. """ hproc = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, thread_pid) try: exit_code = wintypes.DWORD() if GetExitCodeProcess(hproc, byref(exit_code)) != 0: if exit_code == STILL_ACTIVE: return None return int(exit_code) raise WinError() finally: windll.kernel32.CloseHandle(hproc)
def symlink_ms(source, linkname): """Python 2 doesn't have os.symlink on windows so we do it ourselfs :param source: sourceFile :type source: str :param linkname: symlink path :type linkname: str :raises: WindowsError, raises when it fails to create the symlink if the user permissions are incorrect """ import ctypes csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 try: if csl(linkname, source.replace('/', '\\'), flags) == 0: raise ctypes.WinError() except WindowsError: raise WindowsError("Failed to create symbolicLink due to user permissions")
def write(self, data): """Output the given byte string over the serial port.""" if not self._port_handle: raise portNotOpenError #~ if not isinstance(data, (bytes, bytearray)): #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data))) # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview data = to_bytes(data) if data: #~ win32event.ResetEvent(self._overlapped_write.hEvent) n = win32.DWORD() err = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException("WriteFile failed (%r)" % ctypes.WinError()) if self._write_timeout != 0: # if blocking (None) or w/ write timeout (>0) # Wait for the write to complete. #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE) err = win32.GetOverlappedResult(self._port_handle, self._overlapped_write, ctypes.byref(n), True) if n.value != len(data): raise writeTimeoutError return n.value else: return 0
def write(self, data): """Output the given string over the serial port.""" if not self.hComPort: raise portNotOpenError #~ if not isinstance(data, (bytes, bytearray)): #~ raise TypeError('expected %s or bytearray, got %s' % (bytes, type(data))) # convert data (needed in case of memoryview instance: Py 3.1 io lib), ctypes doesn't like memoryview data = to_bytes(data) if data: #~ win32event.ResetEvent(self._overlappedWrite.hEvent) n = win32.DWORD() err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: raise SerialException("WriteFile failed (%r)" % ctypes.WinError()) if self._writeTimeout != 0: # if blocking (None) or w/ write timeout (>0) # Wait for the write to complete. #~ win32.WaitForSingleObject(self._overlappedWrite.hEvent, win32.INFINITE) err = win32.GetOverlappedResult(self.hComPort, self._overlappedWrite, ctypes.byref(n), True) if n.value != len(data): raise writeTimeoutError return n.value else: return 0
def fromEnvironment(cls): """ Get as many of the platform-specific error translation objects as possible and return an instance of C{cls} created with them. """ try: from ctypes import WinError except ImportError: WinError = None try: from win32api import FormatMessage except ImportError: FormatMessage = None try: from socket import errorTab except ImportError: errorTab = None return cls(WinError, FormatMessage, errorTab)
def areAdminRightsElevated(): ''' Tells you whether current script already has Administrative rights. ''' pid = GetCurrentProcess() processToken = HANDLE() if not OpenProcessToken(pid, TOKEN_READ, ctypes.byref(processToken)): raise ctypes.WinError() try: elevated, elevatedSize = DWORD(), DWORD() if not GetTokenInformation(processToken, TokenElevation, ctypes.byref(elevated), ctypes.sizeof(elevated), ctypes.byref(elevatedSize)): raise ctypes.WinError() return bool(elevated) finally: CloseHandle(processToken)
def _is_gui_available(): UOI_FLAGS = 1 WSF_VISIBLE = 0x0001 class USEROBJECTFLAGS(ctypes.Structure): _fields_ = [("fInherit", ctypes.wintypes.BOOL), ("fReserved", ctypes.wintypes.BOOL), ("dwFlags", ctypes.wintypes.DWORD)] dll = ctypes.windll.user32 h = dll.GetProcessWindowStation() if not h: raise ctypes.WinError() uof = USEROBJECTFLAGS() needed = ctypes.wintypes.DWORD() res = dll.GetUserObjectInformationW(h, UOI_FLAGS, ctypes.byref(uof), ctypes.sizeof(uof), ctypes.byref(needed)) if not res: raise ctypes.WinError() return bool(uof.dwFlags & WSF_VISIBLE)
def isatty(): if isatty.no_tty: return False f = sys.stdout if f.isatty(): return True if not iswindows: return False # Check for a cygwin ssh pipe buf = ctypes.create_string_buffer(1024) h = msvcrt.get_osfhandle(f.fileno()) if get_file_type(h) != 3: return False ret = get_file_info_by_handle(h, 2, buf, ctypes.sizeof(buf)) if not ret: raise ctypes.WinError() data = buf.raw name = data[4:].decode('utf-16').rstrip(u'\0') parts = name.split('-') return parts[0] == r'\cygwin' and parts[2].startswith('pty') and parts[4] == 'master'
def _stdout_thread(self, handle, func): # Allocate the output buffer data = ctypes.create_string_buffer(4096) while True: bytesRead = DWORD(0) if not ReadFile(handle, data, 4096, ctypes.byref(bytesRead), None): le = GetLastError() if le == ERROR_BROKEN_PIPE: return else: raise ctypes.WinError() # FIXME: Python3 s = data.value[0:bytesRead.value] #print("\nv: %s" % repr(s), file=sys.stderr) func(s.decode('utf_8', 'replace'))