Python ctypes.FormatError() Examples

The following are 30 code examples of ctypes.FormatError(). 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 ctypes , or try the search function .
Example #1
Source File: network.py    From pydu with MIT License 6 votes vote down vote up
def _win_inet_pton(address_family, ip_str):
        ip_str = safeencode(ip_str)
        addr = _sockaddr()
        addr.sa_family = address_family
        addr_size = ctypes.c_int(ctypes.sizeof(addr))

        if WSAStringToAddressA(
                ip_str,
                address_family,
                None,
                ctypes.byref(addr),
                ctypes.byref(addr_size)
        ) != 0:
            raise socket.error(ctypes.FormatError())

        if address_family == socket.AF_INET:
            return ctypes.string_at(addr.ipv4_addr, 4)
        if address_family == socket.AF_INET6:
            return ctypes.string_at(addr.ipv6_addr, 16)

        raise socket.error('unknown address family') 
Example #2
Source File: win.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _get_window_class(hwnd):
  """Returns the class name of |hwnd|."""
  ctypes.windll.user32.GetClassNameW.restype = ctypes.c_int
  ctypes.windll.user32.GetClassNameW.argtypes = [
      ctypes.c_void_p,  # HWND
      ctypes.c_wchar_p,
      ctypes.c_int
  ]
  name = ctypes.create_unicode_buffer(257)
  name_len = ctypes.windll.user32.GetClassNameW(hwnd, name, len(name))
  if name_len <= 0 or name_len >= len(name):
    raise ctypes.WinError(descr='GetClassNameW failed; %s' %
                          ctypes.FormatError())
  return name.value


## Public API. 
Example #3
Source File: proc_tools.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def pids() -> Iterable[ProcessId]:
        _PROC_ID_T = DWORD
        list_size = 4096

        def try_get_pids(list_size: int) -> List[ProcessId]:
            result_size = DWORD()
            proc_id_list = (_PROC_ID_T * list_size)()

            if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)):
                raise WinError(descr="Failed to get process ID list: %s" % FormatError())  # type: ignore

            return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))])

        while True:
            proc_ids = try_get_pids(list_size)
            if len(proc_ids) < list_size:
                return proc_ids

            list_size *= 2 
Example #4
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def StartYardServer(self):
        try:
            rkey = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Webers\\Y.A.R.D")
            path = RegQueryValueEx(rkey, "program")[0]
            if not os.path.exists(path):
                raise Exception
        except:
            raise self.Exception(
                "Please start Yards.exe first and configure it."
            )
        try:
            hProcess = CreateProcess(
                None,
                path,
                None,
                None,
                0,
                CREATE_NEW_CONSOLE,
                None,
                None,
                STARTUPINFO()
            )[0]
        except Exception, exc:
            raise eg.Exception(FormatError(exc[0])) 
Example #5
Source File: ircsnapshot.py    From ircsnapshot with MIT License 6 votes vote down vote up
def is_ipv6(ip):
    try:
        if os.name == "nt":
            class sockaddr(ctypes.Structure):
                _fields_ = [("sa_family", ctypes.c_short),
                            ("__pad1", ctypes.c_ushort),
                            ("ipv4_addr", ctypes.c_byte * 4),
                            ("ipv6_addr", ctypes.c_byte * 16),
                            ("__pad2", ctypes.c_ulong)]

            WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA
            addr = sockaddr()
            addr.sa_family = socket.AF_INET6
            addr_size = ctypes.c_int(ctypes.sizeof(addr))
            if WSAStringToAddressA(ip, socket.AF_INET6, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0:
                raise socket.error(ctypes.FormatError())
            return ctypes.string_at(addr.ipv6_addr, 16)
        else:
            return socket.inet_pton(socket.AF_INET6, ip)
    except:
        return False 
Example #6
Source File: proc_tools.py    From galaxy-integrations-python-api with MIT License 6 votes vote down vote up
def pids() -> Iterable[ProcessId]:
        _PROC_ID_T = DWORD
        list_size = 4096

        def try_get_pids(list_size: int) -> List[ProcessId]:
            result_size = DWORD()
            proc_id_list = (_PROC_ID_T * list_size)()

            if not windll.psapi.EnumProcesses(byref(proc_id_list), sizeof(proc_id_list), byref(result_size)):
                raise WinError(descr="Failed to get process ID list: %s" % FormatError())  # type: ignore

            return cast(List[ProcessId], proc_id_list[:int(result_size.value / sizeof(_PROC_ID_T()))])

        while True:
            proc_ids = try_get_pids(list_size)
            if len(proc_ids) < list_size:
                return proc_ids

            list_size *= 2 
Example #7
Source File: win_inet_pton.py    From TcpRoute with GNU General Public License v2.0 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #8
Source File: win_inet_pton.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #9
Source File: win_inet_pton.py    From EasY_HaCk with Apache License 2.0 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #10
Source File: win_inet_pton.py    From script.elementum.burst with Do What The F*ck You Want To Public License 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #11
Source File: win_inet_pton.py    From script.elementum.nova with Do What The F*ck You Want To Public License 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #12
Source File: __init__.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def FormatError(code):
        code = int(long(code))
        try:
            if GuessStringType.t_default == GuessStringType.t_ansi:
                FormatMessage = windll.kernel32.FormatMessageA
                FormatMessage.argtypes = [DWORD, LPVOID, DWORD, DWORD, LPSTR, DWORD]
                FormatMessage.restype  = DWORD
                lpBuffer = ctypes.create_string_buffer(1024)
            else:
                FormatMessage = windll.kernel32.FormatMessageW
                FormatMessage.argtypes = [DWORD, LPVOID, DWORD, DWORD, LPWSTR, DWORD]
                FormatMessage.restype  = DWORD
                lpBuffer = ctypes.create_unicode_buffer(1024)
            ##FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
            ##FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
            success = FormatMessage(0x1200, None, code, 0, lpBuffer, 1024)
            if success:
                return lpBuffer.value
        except Exception:
            pass
        if GuessStringType.t_default == GuessStringType.t_ansi:
            return "Error code 0x%.8X" % code
        return u"Error code 0x%.8X" % code 
Example #13
Source File: win_inet_pton.py    From PySyncObj with MIT License 6 votes vote down vote up
def inet_pton(address_family, ip_string):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))

    if WSAStringToAddressA(
            ip_string,
            address_family,
            None,
            ctypes.byref(addr),
            ctypes.byref(addr_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    if address_family == socket.AF_INET:
        return ctypes.string_at(addr.ipv4_addr, 4)
    if address_family == socket.AF_INET6:
        return ctypes.string_at(addr.ipv6_addr, 16)

    raise socket.error('unknown address family') 
Example #14
Source File: utils.py    From anime-dl with MIT License 5 votes vote down vote up
def _lock_file(f, exclusive):
        overlapped = OVERLAPPED()
        overlapped.Offset = 0
        overlapped.OffsetHigh = 0
        overlapped.hEvent = 0
        f._lock_file_overlapped_p = ctypes.pointer(overlapped)
        handle = msvcrt.get_osfhandle(f.fileno())
        if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
                          whole_low, whole_high, f._lock_file_overlapped_p):
            raise OSError('Locking file failed: %r' % ctypes.FormatError()) 
Example #15
Source File: platform_utils_win32.py    From git-repo with Apache License 2.0 5 votes vote down vote up
def _raise_winerror(code, error_desc):
  win_error_desc = FormatError(code).strip()
  error_desc = "%s: %s".format(error_desc, win_error_desc)
  raise WinError(code, error_desc) 
Example #16
Source File: __init__.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def WinError(code=None, descr=None):
        if code is None:
            code = ctypes.GetLastError()
        if descr is None:
            descr = ctypes.FormatError(code).strip()
        return WindowsError(code, descr) 
Example #17
Source File: event.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_exception_description(self):
        """
        @rtype:  str
        @return: User-friendly name of the exception.
        """
        code = self.get_exception_code()
        description = self.__exceptionDescription.get(code, None)
        if description is None:
            try:
                description = 'Exception code %s (%s)'
                description = description % (HexDump.integer(code),
                                             ctypes.FormatError(code))
            except OverflowError:
                description = 'Exception code %s' % HexDump.integer(code)
        return description 
Example #18
Source File: scandir.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def win_error(error, filename):
            exc = WindowsError(error, ctypes.FormatError(error))
            exc.filename = filename
            return exc 
Example #19
Source File: network.py    From pydu with MIT License 5 votes vote down vote up
def _win_inet_ntop(address_family, packed_ip):
        addr = _sockaddr()
        addr.sa_family = address_family
        addr_size = ctypes.c_int(ctypes.sizeof(addr))
        ip_string = ctypes.create_string_buffer(128)
        ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))

        if address_family == socket.AF_INET:
            if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
                raise socket.error('packed IP wrong length for inet_ntoa')
            ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
        elif address_family == socket.AF_INET6:
            if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
                raise socket.error('packed IP wrong length for inet_ntoa')
            ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
        else:
            raise socket.error('unknown address family')

        if WSAAddressToStringA(
                ctypes.byref(addr),
                addr_size,
                None,
                ip_string,
                ctypes.byref(ip_string_size)
        ) != 0:
            raise socket.error(ctypes.FormatError())

        return ip_string[:ip_string_size.value - 1] 
Example #20
Source File: utils.py    From anime-dl with MIT License 5 votes vote down vote up
def _unlock_file(f):
        assert f._lock_file_overlapped_p
        handle = msvcrt.get_osfhandle(f.fileno())
        if not UnlockFileEx(handle, 0,
                            whole_low, whole_high, f._lock_file_overlapped_p):
            raise OSError('Unlocking file failed: %r' % ctypes.FormatError()) 
Example #21
Source File: event.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def get_exception_description(self):
        """
        @rtype:  str
        @return: User-friendly name of the exception.
        """
        code = self.get_exception_code()
        description = self.__exceptionDescription.get(code, None)
        if description is None:
            try:
                description = 'Exception code %s (%s)'
                description = description % (HexDump.integer(code),
                                             ctypes.FormatError(code))
            except OverflowError:
                description = 'Exception code %s' % HexDump.integer(code)
        return description 
Example #22
Source File: scandir.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def win_error(error, filename):
            exc = WindowsError(error, ctypes.FormatError(error))
            exc.filename = filename
            return exc 
Example #23
Source File: win_inet_pton.py    From script.elementum.nova with Do What The F*ck You Want To Public License 5 votes vote down vote up
def inet_ntop(address_family, packed_ip):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))
    ip_string = ctypes.create_string_buffer(128)
    ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))

    if address_family == socket.AF_INET:
        if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
    elif address_family == socket.AF_INET6:
        if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
    else:
        raise socket.error('unknown address family')

    if WSAAddressToStringA(
            ctypes.byref(addr),
            addr_size,
            None,
            ip_string,
            ctypes.byref(ip_string_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    return ip_string[:ip_string_size.value - 1]


# Adding our two functions to the socket library 
Example #24
Source File: win_inet_pton.py    From EasY_HaCk with Apache License 2.0 5 votes vote down vote up
def inet_ntop(address_family, packed_ip):
    addr = sockaddr()
    addr.sa_family = address_family
    addr_size = ctypes.c_int(ctypes.sizeof(addr))
    ip_string = ctypes.create_string_buffer(128)
    ip_string_size = ctypes.c_int(ctypes.sizeof(ip_string))

    if address_family == socket.AF_INET:
        if len(packed_ip) != ctypes.sizeof(addr.ipv4_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv4_addr, packed_ip, 4)
    elif address_family == socket.AF_INET6:
        if len(packed_ip) != ctypes.sizeof(addr.ipv6_addr):
            raise socket.error('packed IP wrong length for inet_ntoa')
        ctypes.memmove(addr.ipv6_addr, packed_ip, 16)
    else:
        raise socket.error('unknown address family')

    if WSAAddressToStringA(
            ctypes.byref(addr),
            addr_size,
            None,
            ip_string,
            ctypes.byref(ip_string_size)
    ) != 0:
        raise socket.error(ctypes.FormatError())

    return ip_string[:ip_string_size.value - 1]

# Adding our two functions to the socket library 
Example #25
Source File: win.py    From Pokemon-Terminal with GNU General Public License v3.0 5 votes vote down vote up
def __raise_last_error():
        err_no = ctypes.GetLastError()
        raise WindowsError(err_no, ctypes.FormatError(err_no)) 
Example #26
Source File: Utils.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def FormatError(code=None):
    """
    A replacement for ctypes.FormtError, but always returns the string
    encoded in CP1252 (ANSI Code Page).
    """
    if code is None:
        code = GetLastError()
    lpMsgBuf = LPWSTR()
    numChars = _kernel32.FormatMessageW(
        (
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS
        ),
        None,
        code,
        0,
        byref(lpMsgBuf),
        0,
        None
    )
    if numChars == 0:
        return "No error message available."
    #raise Exception("FormatMessage failed on 0x%X with 0x%X" % (code & 0xFFFFFFFF, GetLastError()))
    message = lpMsgBuf.value.strip()
    _kernel32.LocalFree(lpMsgBuf)
    return message.encode("CP1252", 'backslashreplace')

# Monkey patch the new FormatError into ctypes 
Example #27
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, imageFileName='', style=1):
        if imageFileName:
            image = wx.Image(imageFileName)
            imageFileName = os.path.join(
                eg.folderPath.RoamingAppData, "Microsoft", "Wallpaper1.bmp"
            )
            image.SaveFile(imageFileName, wx.BITMAP_TYPE_BMP)
        tile, wstyle = (("0", "0"), ("1", "0"), ("0", "2"))[style]
        hKey = _winreg.CreateKey(
            _winreg.HKEY_CURRENT_USER,
            "Control Panel\\Desktop"
        )
        _winreg.SetValueEx(
            hKey,
            "TileWallpaper",
            0,
            _winreg.REG_SZ,
            tile
        )
        _winreg.SetValueEx(
            hKey,
            "WallpaperStyle",
            0,
            _winreg.REG_SZ,
            wstyle
        )
        _winreg.CloseKey(hKey)
        res = SystemParametersInfo(
            SPI_SETDESKWALLPAPER,
            0,
            create_unicode_buffer(imageFileName),
            SPIF_SENDCHANGE | SPIF_UPDATEINIFILE
        )
        if res == 0:
            self.PrintError(ctypes.FormatError()) 
Example #28
Source File: native.py    From wincrypto with MIT License 5 votes vote down vote up
def assert_success(success):
    if not success:
        raise AssertionError(FormatError()) 
Example #29
Source File: utils.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 5 votes vote down vote up
def _handle_errors(rv, src):
        """Handle WinError. Internal use only"""
        if not rv:
            msg = ctypes.FormatError(ctypes.GetLastError())
            # if the MoveFileExW fails(e.g. fail to acquire file lock), removes the tempfile
            try:
                os.remove(src)
            except OSError:
                pass
            finally:
                raise OSError(msg) 
Example #30
Source File: utils.py    From youtube-dl-GUI with MIT License 5 votes vote down vote up
def _unlock_file(f):
        assert f._lock_file_overlapped_p
        handle = msvcrt.get_osfhandle(f.fileno())
        if not UnlockFileEx(handle, 0,
                            whole_low, whole_high, f._lock_file_overlapped_p):
            raise OSError('Unlocking file failed: %r' % ctypes.FormatError())