Python ctypes.windll.kernel32() Examples

The following are 30 code examples for showing how to use ctypes.windll.kernel32(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module ctypes.windll , or try the search function .

Example 1
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _open(self, dwProcessId, debug=False):
        if debug:
            ppsidOwner              = DWORD()
            ppsidGroup              = DWORD()
            ppDacl                  = DWORD()
            ppSacl                  = DWORD()
            ppSecurityDescriptor    = SECURITY_DESCRIPTOR()

            process = kernel32.OpenProcess(262144, 0, dwProcessId)
            advapi32.GetSecurityInfo(kernel32.GetCurrentProcess(), 6, 0, byref(ppsidOwner), byref(ppsidGroup), byref(ppDacl), byref(ppSacl), byref(ppSecurityDescriptor))
            advapi32.SetSecurityInfo(process, 6, DACL_SECURITY_INFORMATION | UNPROTECTED_DACL_SECURITY_INFORMATION, None, None, ppSecurityDescriptor.dacl, ppSecurityDescriptor.group)
            kernel32.CloseHandle(process)
        self.h_process = kernel32.OpenProcess(2035711, 0, dwProcessId)
        if self.h_process is not None:
            self.isProcessOpen = True
            self.pid = dwProcessId
            return True
        return False 
Example 2
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 6 votes vote down vote up
def write_bytes(self, address, data):
        address = int(address)
        if not self.isProcessOpen:
            raise ProcessException("Can't write_bytes(%s, %s), process %s is not open" % (address, data, self.pid))
        buffer = create_string_buffer(data)
        sizeWriten = c_size_t(0)
        bufferSize = sizeof(buffer) - 1
        _address = address
        _length = bufferSize + 1
        try:
            old_protect = self.VirtualProtectEx(_address, _length, PAGE_EXECUTE_READWRITE)
        except:
            pass

        res = kernel32.WriteProcessMemory(self.h_process, address, buffer, bufferSize, byref(sizeWriten))
        try:
            self.VirtualProtectEx(_address, _length, old_protect)
        except:
            pass

        return res 
Example 3
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 6 votes vote down vote up
def _get_geometry(self):
        """Get details about the disk size bounds."""
        geom = Win32_DiskGeometry()
        bytes_returned = wintypes.DWORD()
        ret_val = kernel32.DeviceIoControl(
            self._handle,
            winioctlcon.IOCTL_DISK_GET_DRIVE_GEOMETRY,
            0,
            0,
            ctypes.byref(geom),
            ctypes.sizeof(geom),
            ctypes.byref(bytes_returned),
            0)

        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "Cannot get disk geometry: %r")

        _sector_size = geom.BytesPerSector
        _disk_size = (geom.Cylinders * geom.TracksPerCylinder *
                      geom.SectorsPerTrack * geom.BytesPerSector)
        fixed = geom.MediaType == Win32_DiskGeometry.FixedMedia
        return _sector_size, _disk_size, fixed 
Example 4
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 6 votes vote down vote up
def open(self):
        access = self.GENERIC_READ
        share_mode = self.FILE_SHARE_READ
        if self._allow_write:
            access |= self.GENERIC_WRITE
            share_mode |= self.FILE_SHARE_WRITE
            attributes = 0
        else:
            attributes = self.FILE_ATTRIBUTE_READONLY

        handle = kernel32.CreateFileW(
            ctypes.c_wchar_p(self._path),
            access,
            share_mode,
            0,
            self.OPEN_EXISTING,
            attributes,
            0)
        if handle == self.INVALID_HANDLE_VALUE:
            raise exception.WindowsCloudbaseInitException(
                'Cannot open file: %r')
        self._handle = handle
        self._sector_size, self._disk_size, self.fixed =\
            self._get_geometry() 
Example 5
Project: luci-py   Author: luci   File: fix_encoding.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, console_handle, fileno, stream_name, encoding):
    super(WinUnicodeConsoleOutput, self).__init__(
        fileno, '<Unicode console %s>' % stream_name, encoding)
    # Handle to use for WriteConsoleW
    self._console_handle = console_handle

    # Loads the necessary function.
    # These types are available on linux but not Mac.
    # pylint: disable=no-name-in-module,F0401
    from ctypes import byref, GetLastError, POINTER, windll, WINFUNCTYPE
    from ctypes.wintypes import BOOL, DWORD, HANDLE, LPWSTR
    from ctypes.wintypes import LPVOID  # pylint: disable=no-name-in-module

    self._DWORD = DWORD
    self._byref = byref

    # <http://msdn.microsoft.com/en-us/library/ms687401.aspx>
    self._WriteConsoleW = WINFUNCTYPE(
        BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(
            ('WriteConsoleW', windll.kernel32))
    self._GetLastError = GetLastError 
Example 6
Project: luci-py   Author: luci   File: fix_encoding.py    License: Apache License 2.0 6 votes vote down vote up
def win_handle_is_a_console(handle):
  """Returns True if a Windows file handle is a handle to a console."""
  # These types are available on linux but not Mac.
  # pylint: disable=no-name-in-module,F0401
  from ctypes import byref, POINTER, windll, WINFUNCTYPE
  from ctypes.wintypes import BOOL, DWORD, HANDLE

  FILE_TYPE_CHAR   = 0x0002
  FILE_TYPE_REMOTE = 0x8000
  INVALID_HANDLE_VALUE = DWORD(-1).value

  # <http://msdn.microsoft.com/en-us/library/ms683167.aspx>
  GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
      ('GetConsoleMode', windll.kernel32))
  # <http://msdn.microsoft.com/en-us/library/aa364960.aspx>
  GetFileType = WINFUNCTYPE(DWORD, DWORD)(('GetFileType', windll.kernel32))

  # GetStdHandle returns INVALID_HANDLE_VALUE, NULL, or a valid handle.
  if handle == INVALID_HANDLE_VALUE or handle is None:
    return False
  return (
      (GetFileType(handle) & ~FILE_TYPE_REMOTE) == FILE_TYPE_CHAR and
       GetConsoleMode(handle, byref(DWORD()))) 
Example 7
Project: patch_linemod   Author: meiqua   File: t-less_download.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def win32_utf8_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    argnum = argc.value
    sysnum = len(sys.argv)
    result = []
    if argnum > 0:
        # Remove Python executable and commands if present
        start = argnum - sysnum
        for i in range(start, argnum):
            result.append(argv[i].encode('utf-8'))
    return result


# enable unicode output to windows console
# https://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash 
Example 8
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list():
        processes=[]
        arr = c_ulong * 256
        lpidProcess= arr()
        cb = sizeof(lpidProcess)
        cbNeeded = c_ulong()
        hModule = c_ulong()
        count = c_ulong()
        modname = create_string_buffer(100)
        PROCESS_QUERY_INFORMATION = 0x0400
        PROCESS_VM_READ = 0x0010

        psapi.EnumProcesses(byref(lpidProcess), cb, byref(cbNeeded))
        nReturned = cbNeeded.value/sizeof(c_ulong())

        pidProcess = [i for i in lpidProcess][:nReturned]
        for pid in pidProcess:
            proc={ "pid": int(pid) }
            hProcess = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
            if hProcess:
                psapi.EnumProcessModules(hProcess, byref(hModule), sizeof(hModule), byref(count))
                psapi.GetModuleBaseNameA(hProcess, hModule.value, modname, sizeof(modname))
                proc["name"]=modname.value
                kernel32.CloseHandle(hProcess)
            processes.append(proc)
        return processes 
Example 9
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close(self):
        if self.h_process is not None:
            ret = kernel32.CloseHandle(self.h_process) == 1
            if ret:
                self.h_process = None
                self.pid = None
                self.isProcessOpen = False
            return ret
        return False 
Example 10
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 5 votes vote down vote up
def GetSystemInfo(self):
        si = SYSTEM_INFO()
        kernel32.GetSystemInfo(byref(si))
        return si 
Example 11
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 5 votes vote down vote up
def GetNativeSystemInfo(self):
        si = SYSTEM_INFO()
        kernel32.GetNativeSystemInfo(byref(si))
        return si 
Example 12
Project: memorpy   Author: n1nj4sec   File: WinProcess.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list_modules(self):
        module_list = []
        if self.pid is not None:
            hModuleSnap = CreateToolhelp32Snapshot(TH32CS_CLASS.SNAPMODULE, self.pid)
            if hModuleSnap is not None:
                module_entry = MODULEENTRY32()
                module_entry.dwSize = sizeof(module_entry)
                success = Module32First(hModuleSnap, byref(module_entry))
                while success:
                    if module_entry.th32ProcessID == self.pid:
                        module_list.append(copy.copy(module_entry))
                    success = Module32Next(hModuleSnap, byref(module_entry))

                kernel32.CloseHandle(hModuleSnap)
        return module_list 
Example 13
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 5 votes vote down vote up
def _seek(self, offset):
        high = wintypes.DWORD(offset >> 32)
        low = wintypes.DWORD(offset & 0xFFFFFFFF)

        ret_val = kernel32.SetFilePointer(self._handle, low,
                                          ctypes.byref(high),
                                          self.FILE_BEGIN)
        if ret_val == self.INVALID_SET_FILE_POINTER:
            raise exception.WindowsCloudbaseInitException(
                "Seek error: %r") 
Example 14
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 5 votes vote down vote up
def _read(self, size):
        buff = ctypes.create_string_buffer(size)
        bytes_read = wintypes.DWORD()
        ret_val = kernel32.ReadFile(self._handle, buff, size,
                                    ctypes.byref(bytes_read), 0)
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "Read exception: %r")
        return buff.raw[:bytes_read.value]    # all bytes without the null byte 
Example 15
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 5 votes vote down vote up
def close(self):
        if self._handle:
            kernel32.CloseHandle(self._handle)
            self._handle = None 
Example 16
Project: cloudbase-init   Author: cloudbase   File: disk.py    License: Apache License 2.0 5 votes vote down vote up
def set_unique_id(self, unique_id=None):
        layout = self._get_layout()
        if layout.PartitionStyle == self.PARTITION_STYLE_MBR:
            if not unique_id:
                unique_id = random.randint(-2147483648, 2147483647)
            layout.Mbr.Signature = unique_id
        elif layout.PartitionStyle == self.PARTITION_STYLE_GPT:
            if not unique_id:
                unique_id = self._create_guid()
            layout.Gpt.DiskId = unique_id
        else:
            raise exception.InvalidStateException(
                "A unique id can be set on MBR or GPT partitions only")

        bytes_returned = wintypes.DWORD()
        ret_val = kernel32.DeviceIoControl(
            self._handle, winioctlcon.IOCTL_DISK_SET_DRIVE_LAYOUT_EX,
            ctypes.byref(layout), ctypes.sizeof(layout), 0, 0,
            ctypes.byref(bytes_returned), 0)
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "Cannot set disk layout: %r")

        ret_val = kernel32.DeviceIoControl(
            self._handle, winioctlcon.IOCTL_DISK_UPDATE_PROPERTIES, 0, 0, 0, 0,
            ctypes.byref(bytes_returned), 0)
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "Cannot update cached disk properties: %r") 
Example 17
Project: slither   Author: crytic   File: colors.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def enable_windows_virtual_terminal_sequences():
    """
    Sets the appropriate flags to enable virtual terminal sequences in a Windows command prompt.
    Reference: https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences
    """

    try:
        from ctypes import windll, byref
        from ctypes.wintypes import DWORD, HANDLE

        kernel32 = windll.kernel32
        virtual_terminal_flag = 0x04  # ENABLE_VIRTUAL_TERMINAL_PROCESSING

        # Obtain our stdout/stderr handles.
        # Reference: https://docs.microsoft.com/en-us/windows/console/getstdhandle
        handle_stdout = kernel32.GetStdHandle(-11)
        handle_stderr = kernel32.GetStdHandle(-12)

        # Loop for each stdout/stderr handle.
        for current_handle in [handle_stdout, handle_stderr]:

            # If we get a null handle, or fail any subsequent calls in this scope, we do not colorize any output.
            if current_handle is None or current_handle == HANDLE(-1):
                return False

            # Try to obtain the current flags for the console.
            current_mode = DWORD()
            if not kernel32.GetConsoleMode(current_handle, byref(current_mode)):
                return False

            # If the virtual terminal sequence processing is not yet enabled, we enable it.
            if (current_mode.value & virtual_terminal_flag) == 0:
                if not kernel32.SetConsoleMode(current_handle, current_mode.value | virtual_terminal_flag):
                    return False
    except:
        # Any generic failure (possibly from calling these methods on older Windows builds where they do not exist)
        # will fall back onto disabling colorization.
        return False

    return True 
Example 18
Project: NoobSec-Toolkit   Author: krintoxi   File: mouselogger.py    License: GNU General Public License v2.0 5 votes vote down vote up
def install_hook(self):
		CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
		self.pointer = CMPFUNC(self.hook_proc)
		self.hooked = self.lUser32.SetWindowsHookExA(WH_MOUSE_LL, self.pointer, kernel32.GetModuleHandleW(None), 0)
		if not self.hooked:
			return False
		return True 
Example 19
Project: NoobSec-Toolkit   Author: krintoxi   File: processes.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_process_64(pid):
	""" Take a pid. return True if process is 64 bits, and False otherwise. """
	is64=False
	if not "64" in platform.machine():
		return False
	hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
	is64=is_process_64_from_handle(hProcess)
	windll.kernel32.CloseHandle(hProcess)
	return is64 
Example 20
Project: NoobSec-Toolkit   Author: krintoxi   File: processes.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_process_64_from_handle(hProcess):
	""" Take a process handle. return True if process is 64 bits, and False otherwise. """
	iswow64 = c_bool(False)
	if not hasattr(windll.kernel32,'IsWow64Process'):
		return False
	windll.kernel32.IsWow64Process(hProcess, byref(iswow64))
	return not iswow64.value 
Example 21
Project: NoobSec-Toolkit   Author: krintoxi   File: mouselogger.py    License: GNU General Public License v2.0 5 votes vote down vote up
def install_hook(self):
		CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
		self.pointer = CMPFUNC(self.hook_proc)
		self.hooked = self.lUser32.SetWindowsHookExA(WH_MOUSE_LL, self.pointer, kernel32.GetModuleHandleW(None), 0)
		if not self.hooked:
			return False
		return True 
Example 22
Project: NoobSec-Toolkit   Author: krintoxi   File: processes.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_process_64(pid):
	""" Take a pid. return True if process is 64 bits, and False otherwise. """
	is64=False
	if not "64" in platform.machine():
		return False
	hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
	is64=is_process_64_from_handle(hProcess)
	windll.kernel32.CloseHandle(hProcess)
	return is64 
Example 23
Project: pre-commit   Author: pre-commit   File: color.py    License: MIT License 5 votes vote down vote up
def _enable() -> None:
        from ctypes import POINTER
        from ctypes import windll
        from ctypes import WinError
        from ctypes import WINFUNCTYPE
        from ctypes.wintypes import BOOL
        from ctypes.wintypes import DWORD
        from ctypes.wintypes import HANDLE

        STD_ERROR_HANDLE = -12
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

        def bool_errcheck(result, func, args):
            if not result:
                raise WinError()
            return args

        GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
            ('GetStdHandle', windll.kernel32), ((1, 'nStdHandle'),),
        )

        GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
            ('GetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (2, 'lpMode')),
        )
        GetConsoleMode.errcheck = bool_errcheck

        SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
            ('SetConsoleMode', windll.kernel32),
            ((1, 'hConsoleHandle'), (1, 'dwMode')),
        )
        SetConsoleMode.errcheck = bool_errcheck

        # As of Windows 10, the Windows console supports (some) ANSI escape
        # sequences, but it needs to be enabled using `SetConsoleMode` first.
        #
        # More info on the escape sequences supported:
        # https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
        stderr = GetStdHandle(STD_ERROR_HANDLE)
        flags = GetConsoleMode(stderr)
        SetConsoleMode(stderr, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING) 
Example 24
Project: luci-py   Author: luci   File: fix_encoding.py    License: Apache License 2.0 5 votes vote down vote up
def win_get_unicode_stream(stream, excepted_fileno, output_handle, encoding):
  """Returns a unicode-compatible stream.

  This function will return a direct-Console writing object only if:
  - the file number is the expected console file number
  - the handle the expected file handle
  - the 'real' handle is in fact a handle to a console.
  """
  old_fileno = getattr(stream, 'fileno', lambda: None)()
  if old_fileno == excepted_fileno:
    # These types are available on linux but not Mac.
    # pylint: disable=no-name-in-module,F0401
    from ctypes import windll, WINFUNCTYPE
    from ctypes.wintypes import DWORD, HANDLE

    # <http://msdn.microsoft.com/en-us/library/ms683231.aspx>
    GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(('GetStdHandle', windll.kernel32))

    real_output_handle = GetStdHandle(DWORD(output_handle))
    if win_handle_is_a_console(real_output_handle):
      # It's a console.
      return WinUnicodeConsoleOutput(
          real_output_handle, old_fileno, stream.name, encoding)

  # It's something else. Create an auto-encoding stream.
  return WinUnicodeOutput(stream, old_fileno, encoding) 
Example 25
Project: VKMusicDownloader   Author: keyzt   File: wget.py    License: MIT License 5 votes vote down vote up
def win32_utf8_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    argnum = argc.value
    sysnum = len(sys.argv)
    result = []
    if argnum > 0:
        # Remove Python executable and commands if present
        start = argnum - sysnum
        for i in range(start, argnum):
            result.append(argv[i].encode('utf-8'))
    return result


# enable unicode output to windows console
# https://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash 
Example 26
Project: backdoorme   Author: Kkevsterrr   File: mouselogger.py    License: MIT License 5 votes vote down vote up
def install_hook(self):
		CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
		self.pointer = CMPFUNC(self.hook_proc)
		self.hooked = self.lUser32.SetWindowsHookExA(WH_MOUSE_LL, self.pointer, kernel32.GetModuleHandleW(None), 0)
		if not self.hooked:
			return False
		return True 
Example 27
Project: backdoorme   Author: Kkevsterrr   File: processes.py    License: MIT License 5 votes vote down vote up
def is_process_64(pid):
	""" Take a pid. return True if process is 64 bits, and False otherwise. """
	is64=False
	if not "64" in platform.machine():
		return False
	hProcess = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
	is64=is_process_64_from_handle(hProcess)
	windll.kernel32.CloseHandle(hProcess)
	return is64 
Example 28
Project: backdoorme   Author: Kkevsterrr   File: processes.py    License: MIT License 5 votes vote down vote up
def is_process_64_from_handle(hProcess):
	""" Take a process handle. return True if process is 64 bits, and False otherwise. """
	iswow64 = c_bool(False)
	if not hasattr(windll.kernel32,'IsWow64Process'):
		return False
	windll.kernel32.IsWow64Process(hProcess, byref(iswow64))
	return not iswow64.value 
Example 29
Project: patch_linemod   Author: meiqua   File: t-less_download.py    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
def get_console_width():
    """Return width of available window area. Autodetection works for
       Windows and POSIX platforms. Returns 80 for others

       Code from http://bitbucket.org/techtonik/python-pager
    """

    if os.name == 'nt':
        STD_INPUT_HANDLE  = -10
        STD_OUTPUT_HANDLE = -11
        STD_ERROR_HANDLE  = -12

        # get console handle
        from ctypes import windll, Structure, byref
        try:
            from ctypes.wintypes import SHORT, WORD, DWORD
        except ImportError:
            # workaround for missing types in Python 2.5
            from ctypes import (
                c_short as SHORT, c_ushort as WORD, c_ulong as DWORD)
        console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

        # CONSOLE_SCREEN_BUFFER_INFO Structure
        class COORD(Structure):
            _fields_ = [("X", SHORT), ("Y", SHORT)]

        class SMALL_RECT(Structure):
            _fields_ = [("Left", SHORT), ("Top", SHORT),
                        ("Right", SHORT), ("Bottom", SHORT)]

        class CONSOLE_SCREEN_BUFFER_INFO(Structure):
            _fields_ = [("dwSize", COORD),
                        ("dwCursorPosition", COORD),
                        ("wAttributes", WORD),
                        ("srWindow", SMALL_RECT),
                        ("dwMaximumWindowSize", DWORD)]

        sbi = CONSOLE_SCREEN_BUFFER_INFO()
        ret = windll.kernel32.GetConsoleScreenBufferInfo(
            console_handle, byref(sbi))
        if ret == 0:
            return 0
        return sbi.srWindow.Right+1

    elif os.name == 'posix':
        from fcntl import ioctl
        from termios import TIOCGWINSZ
        from array import array

        winsize = array("H", [0] * 4)
        try:
            ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize)
        except IOError:
            pass
        return (winsize[1], winsize[0])[0]

    return 80 
Example 30
Project: teleport   Author: tp4a   File: logger.py    License: Apache License 2.0 4 votes vote down vote up
def __init__(self):
        from ctypes import WINFUNCTYPE, windll
        from ctypes.wintypes import BOOL, HANDLE, DWORD, WORD

        self.__original_stderr = sys.stderr
        self.__stdout = None
        self.__SetConsoleTextAttribute = None

        # Work around <http://bugs.python.org/issue6058>.
        # codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)

        # Make Unicode console output work independently of the current code page.
        # This also fixes <http://bugs.python.org/issue1602>.
        # Credit to Michael Kaplan <http://blogs.msdn.com/b/michkap/archive/2010/04/07/9989346.aspx>
        # and TZOmegaTZIOY
        # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
        try:
            # <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
            # HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
            # returns INVALID_HANDLE_VALUE, NULL, or a valid handle
            #
            # <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
            # DWORD WINAPI GetFileType(DWORD hFile);
            #
            # <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
            # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);

            STD_OUTPUT_HANDLE = DWORD(-11)
            INVALID_HANDLE_VALUE = DWORD(-1).value

            GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))

            self.__SetConsoleTextAttribute = WINFUNCTYPE(BOOL, HANDLE, WORD)(("SetConsoleTextAttribute", windll.kernel32))

            self.__stdout = GetStdHandle(STD_OUTPUT_HANDLE)
            if self.__stdout == INVALID_HANDLE_VALUE:
                self.__stdout = None

        except Exception as e:
            self.__stdout = None
            self._complain("exception %r while fixing up sys.stdout and sys.stderr\n" % (str(e),))

    # If any exception occurs in this code, we'll probably try to print it on stderr,
    # which makes for frustrating debugging if stderr is directed to our wrapper.
    # So be paranoid about catching errors and reporting them to original_stderr,
    # so that we can at least see them.