当前位置: 首页>>代码示例>>Python>>正文


Python ctypes.get_last_error方法代码示例

本文整理汇总了Python中ctypes.get_last_error方法的典型用法代码示例。如果您正苦于以下问题:Python ctypes.get_last_error方法的具体用法?Python ctypes.get_last_error怎么用?Python ctypes.get_last_error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ctypes的用法示例。


在下文中一共展示了ctypes.get_last_error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: enum_pids

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def enum_pids():
	
	max_array = c_ulong * 4096 # define long array to capture all the processes
	pProcessIds = max_array() # array to store the list of processes
	pBytesReturned = c_ulong() # the number of bytes returned in the array
	#EnumProcess 
	res = EnumProcesses(
		ctypes.byref(pProcessIds),
		ctypes.sizeof(pProcessIds),
		ctypes.byref(pBytesReturned)
	)
	if res == 0:
		logging.error(WinError(get_last_error()))
		return []
  
	# get the number of returned processes
	nReturned = int(pBytesReturned.value/ctypes.sizeof(c_ulong()))
	return [i for i in pProcessIds[:nReturned]]
	
#https://msdn.microsoft.com/en-us/library/windows/desktop/ms683217(v=vs.85).aspx 
开发者ID:skelsec,项目名称:minidump,代码行数:22,代码来源:createminidump.py

示例2: enum_process_names

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def enum_process_names():
	pid_to_name = {}
	
	for pid in enum_pids():
		pid_to_name[pid] = 'Not found'
		process_handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
		if process_handle is None:
			logging.debug('[Enum Processes]Failed to open process PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		image_name = (ctypes.c_char*MAX_PATH)()
		max_path = DWORD(4096)
		#res = GetProcessImageFileName(process_handle, image_name, MAX_PATH)
		res = QueryFullProcessImageName(process_handle, 0 ,image_name, ctypes.byref(max_path))
		if res == 0:
			logging.debug('[Enum Proceses]Failed GetProcessImageFileName on PID: %d Reason: %s ' % (pid, WinError(get_last_error())))
			continue
		
		pid_to_name[pid] = image_name.value.decode()
	return pid_to_name 
开发者ID:skelsec,项目名称:minidump,代码行数:22,代码来源:createminidump.py

示例3: set_kill_child_on_death_win32

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def set_kill_child_on_death_win32(child_proc):
    """Ensures the child process dies if this process dies (fate-sharing).

    Windows-only. Must be called by the parent, after spawning the child.

    Args:
        child_proc: The subprocess.Popen or subprocess.Handle object.
    """

    if isinstance(child_proc, subprocess.Popen):
        child_proc = child_proc._handle
    assert isinstance(child_proc, subprocess.Handle)

    if detect_fate_sharing_support_win32():
        if not win32_AssignProcessToJobObject(win32_job, int(child_proc)):
            import ctypes
            raise OSError(ctypes.get_last_error(),
                          "AssignProcessToJobObject() failed")
    else:
        assert False, "AssignProcessToJobObject used despite being unavailable" 
开发者ID:ray-project,项目名称:ray,代码行数:22,代码来源:utils.py

示例4: readinto

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def readinto(self, b):
		bytes_to_be_read = len(b)
		if not bytes_to_be_read:
			return 0
		elif bytes_to_be_read % 2:
			raise ValueError("cannot read odd number of bytes from UTF-16-LE encoded console")
		
		buffer = get_buffer(b, writable=True)
		code_units_to_be_read = bytes_to_be_read // 2
		code_units_read = c_ulong()
		
		set_last_error(ERROR_SUCCESS)
		ReadConsoleW(self.handle, buffer, code_units_to_be_read, byref(code_units_read), None)
		last_error = get_last_error()
		if last_error == ERROR_OPERATION_ABORTED:
			time.sleep(0.1)	# wait for KeyboardInterrupt
		if last_error != ERROR_SUCCESS:
			raise WinError(last_error)
		
		if buffer[0] == EOF:
			return 0
		else:
			return 2 * code_units_read.value # bytes read 
开发者ID:Drekin,项目名称:win-unicode-console,代码行数:25,代码来源:streams.py

示例5: write

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def write(self, b):
		bytes_to_be_written = len(b)
		buffer = get_buffer(b)
		code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
		code_units_written = c_ulong()
		
		if code_units_to_be_written == 0 != bytes_to_be_written:
			raise ValueError("two-byte code units expected, just one byte given")
		
		if not WriteConsoleW(self.handle, buffer, code_units_to_be_written, byref(code_units_written), None):
			exc = WinError(get_last_error())
			if exc.winerror == ERROR_NOT_ENOUGH_MEMORY:
				exc.strerror += " Try to lower `win_unicode_console.streams.MAX_BYTES_WRITTEN`."
			raise exc
		
		return 2 * code_units_written.value # bytes written 
开发者ID:Drekin,项目名称:win-unicode-console,代码行数:18,代码来源:streams.py

示例6: is64bitProc

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def is64bitProc(process_handle):
	is64 = BOOL()
	res = IsWow64Process(process_handle, ctypes.byref(is64))
	if res == 0:
		logging.warning('Failed to get process version info!')
		WinError(get_last_error())
	return not bool(is64.value)
	
# https://waitfordebug.wordpress.com/2012/01/27/pid-enumeration-on-windows-with-pure-python-ctypes/ 
开发者ID:skelsec,项目名称:minidump,代码行数:11,代码来源:createminidump.py

示例7: create_dump

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def create_dump(pid, output_filename, mindumptype, with_debug = False):
	if with_debug:
		logging.debug('Enabling SeDebugPrivilege')
		assigned = enable_debug_privilege()
		msg = ['failure', 'success'][assigned]
		logging.debug('SeDebugPrivilege assignment %s' % msg)
	
	logging.debug('Opening process PID: %d' % pid)
	process_handle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
	if process_handle is None:
		logging.warning('Failed to open process PID: %d' % pid)
		logging.error(WinError(get_last_error()))
		return
	logging.debug('Process handle: 0x%04x' % process_handle)
	is64 = is64bitProc(process_handle)
	if is64 != IS_PYTHON_64:
		logging.warning('process architecture mismatch! This could case error! Python arch: %s Target process arch: %s' % ('x86' if not IS_PYTHON_64 else 'x64', 'x86' if not is64 else 'x64'))
	
	logging.debug('Creating file handle for output file')
	file_handle = CreateFile(output_filename, FILE_GENERIC_READ | FILE_GENERIC_WRITE, 0, None,  FILE_CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, None)
	if file_handle == -1:
		logging.warning('Failed to create file')
		logging.error(WinError(get_last_error()))
		return
	logging.debug('Dumping process to file')
	res = MiniDumpWriteDump(process_handle, pid, file_handle, mindumptype, 0,0,0)
	if not bool(res):
		logging.warning('Failed to dump process to file')
		logging.error(WinError(get_last_error()))
	logging.info('Dump file created succsessfully')
	CloseHandle(file_handle)
	CloseHandle(process_handle) 
开发者ID:skelsec,项目名称:minidump,代码行数:34,代码来源:createminidump.py

示例8: get_errno

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def get_errno():
        raise NotImplementedError(
            'Your python version does not support errno/last_error'
        ) 
开发者ID:luci,项目名称:luci-py,代码行数:6,代码来源:usb1.py

示例9: getPollFDList

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def getPollFDList(self):
        """
        Return file descriptors to be used to poll USB events.
        You should not have to call this method, unless you are integrating
        this class with a polling mechanism.
        """
        pollfd_p_p = libusb1.libusb_get_pollfds(self.__context_p)
        if not pollfd_p_p:
            errno = get_errno()
            if errno:
                raise OSError(errno)
            else:
                # Assume not implemented
                raise NotImplementedError(
                    'Your libusb does not seem to implement pollable FDs')
        try:
            result = []
            append = result.append
            fd_index = 0
            while pollfd_p_p[fd_index]:
                append((
                    pollfd_p_p[fd_index].contents.fd,
                    pollfd_p_p[fd_index].contents.events,
                ))
                fd_index += 1
        finally:
            _free(pollfd_p_p)
        return result 
开发者ID:luci,项目名称:luci-py,代码行数:30,代码来源:usb1.py

示例10: enable_ctrl_c_support

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def enable_ctrl_c_support() -> None:
    """Enable ctrl+c support for aea.cli command to be tested on windows platform."""
    if platform.system() != "Windows":
        return

    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)  # type: ignore

    if not kernel32.SetConsoleCtrlHandler(None, False):
        logger.debug(f"SetConsoleCtrlHandler Error: {ctypes.get_last_error()}")  # type: ignore 
开发者ID:fetchai,项目名称:agents-aea,代码行数:11,代码来源:win32.py

示例11: _create_symlink

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def _create_symlink(source, link_name, dwFlags):
  if not CreateSymbolicLinkW(link_name, source,
                             dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
    # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
    # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
    # retry without it."
    if not CreateSymbolicLinkW(link_name, source, dwFlags):
      code = get_last_error()
      error_desc = FormatError(code).strip()
      if code == ERROR_PRIVILEGE_NOT_HELD:
        raise OSError(errno.EPERM, error_desc, link_name)
      _raise_winerror(
          code,
          'Error creating symbolic link \"%s\"'.format(link_name)) 
开发者ID:GerritCodeReview,项目名称:git-repo,代码行数:16,代码来源:platform_utils_win32.py

示例12: readlink

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def readlink(path):
  reparse_point_handle = CreateFileW(path,
                                     0,
                                     0,
                                     None,
                                     OPEN_EXISTING,
                                     FILE_FLAG_OPEN_REPARSE_POINT |
                                     FILE_FLAG_BACKUP_SEMANTICS,
                                     None)
  if reparse_point_handle == INVALID_HANDLE_VALUE:
    _raise_winerror(
        get_last_error(),
        'Error opening symbolic link \"%s\"'.format(path))
  target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
  n_bytes_returned = DWORD()
  io_result = DeviceIoControl(reparse_point_handle,
                              FSCTL_GET_REPARSE_POINT,
                              None,
                              0,
                              target_buffer,
                              len(target_buffer),
                              byref(n_bytes_returned),
                              None)
  CloseHandle(reparse_point_handle)
  if not io_result:
    _raise_winerror(
        get_last_error(),
        'Error reading symbolic link \"%s\"'.format(path))
  rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
  if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
    return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
  elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
    return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
  # Unsupported reparse point type
  _raise_winerror(
      ERROR_NOT_SUPPORTED,
      'Error reading symbolic link \"%s\"'.format(path)) 
开发者ID:GerritCodeReview,项目名称:git-repo,代码行数:39,代码来源:platform_utils_win32.py

示例13: check_fifo

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def check_fifo(fifo):
    if sys.platform == 'win32':
        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
        handle = msvcrt.get_osfhandle(fifo.fileno())
        data = b''
        p_data = ctypes.c_char_p(data)
        written = ctypes.c_ulong(0)
        while True:
            time.sleep(FIFO_CHECK_INTERVAL)
            if not kernel32.WriteFile(handle, p_data, 0, ctypes.byref(written),
                                      None):
                error = ctypes.get_last_error()
                if error in (
                        0xe8,  # ERROR_NO_DATA
                        0xe9,  # ERROR_PIPE_NOT_CONNECTED
                ):
                    os._exit(0)
                else:
                    raise ctypes.WinError(error)
    else:
        while True:
            time.sleep(FIFO_CHECK_INTERVAL)
            try:
                os.stat(fifo.name)
            except OSError:
                os._exit(0) 
开发者ID:openthread,项目名称:pyspinel,代码行数:28,代码来源:sniffer.py

示例14: is_a_console

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def is_a_console(self):
		if self.handle is None:
			return False
		
		if GetConsoleMode(self.handle, byref(c_ulong())):
			return True
		else:
			last_error = get_last_error()
			if last_error == ERROR_INVALID_HANDLE:
				return False
			else:
				raise WinError(last_error) 
开发者ID:Drekin,项目名称:win-unicode-console,代码行数:14,代码来源:streams.py

示例15: _check_alloc_console

# 需要导入模块: import ctypes [as 别名]
# 或者: from ctypes import get_last_error [as 别名]
def _check_alloc_console(self) -> None:
        if sys.executable.endswith("pythonw.exe"):
            # These don't have console allocated.
            # Console is required for sending interrupts.

            # AllocConsole would be easier but flashes console window

            import ctypes

            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)

            exe = sys.executable.replace("pythonw.exe", "python.exe")

            cmd = [exe, "-c", "print('Hi!'); input()"]
            child = subprocess.Popen(
                cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=True,
            )
            child.stdout.readline()
            result = kernel32.AttachConsole(child.pid)
            if not result:
                err = ctypes.get_last_error()
                logging.info("Could not allocate console. Error code: " + str(err))
            child.stdin.write(b"\n")
            try:
                child.stdin.flush()
            except Exception:
                # May happen eg. when installation path has "&" in it
                # See https://bitbucket.org/plas/thonny/issues/508/cant-allocate-windows-console-when
                # Without flush the console window becomes visible, but Thonny can be still used
                logging.getLogger("thonny").exception("Problem with finalizing console allocation") 
开发者ID:thonny,项目名称:thonny,代码行数:36,代码来源:running.py


注:本文中的ctypes.get_last_error方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。