Python ctypes.wintypes.LPCWSTR Examples

The following are 30 code examples of ctypes.wintypes.LPCWSTR(). 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.wintypes , or try the search function .
Example #1
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def Put(self, name, val, flavor):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.POINTER(winapi.VARIANT),
                                       ctypes.c_long)

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'pVal'),
                      (_In_, 'lFlavor'),
                      )

        _Put = prototype(IWbemQualifierSet_Put_Idx,
                         'Put',
                         paramflags)
        _Put.errcheck = winapi.RAISE_NON_ZERO_ERR
        _Put(self.this,
             name,
             ctypes.byref(val) if val else None,
             flavor
             ) 
Example #2
Source File: utils.py    From JediHTTP with Apache License 2.0 6 votes vote down vote up
def get_short_path_name(path):
    from ctypes import windll, wintypes, create_unicode_buffer

    # Set the GetShortPathNameW prototype
    _GetShortPathNameW = windll.kernel32.GetShortPathNameW
    _GetShortPathNameW.argtypes = [wintypes.LPCWSTR,
                                   wintypes.LPWSTR,
                                   wintypes.DWORD]
    _GetShortPathNameW.restype = wintypes.DWORD

    output_buf_size = 0

    while True:
        output_buf = create_unicode_buffer(output_buf_size)
        needed = _GetShortPathNameW(path, output_buf, output_buf_size)
        if output_buf_size >= needed:
            return output_buf.value
        output_buf_size = needed


# A wrapper for subprocess.Popen that fixes quirks on Windows. 
Example #3
Source File: plat_win.py    From pipeline with MIT License 6 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + '\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        msg = "Couldn't perform operation. Error code: %d" % result
        raise OSError(msg) 
Example #4
Source File: _process_win32.py    From Computable with MIT License 6 votes vote down vote up
def arg_split(commandline, posix=False, strict=True):
        """Split a command line's arguments in a shell-like manner.

        This is a special version for windows that use a ctypes call to CommandLineToArgvW
        to do the argv splitting. The posix paramter is ignored.
        
        If strict=False, process_common.arg_split(...strict=False) is used instead.
        """
        #CommandLineToArgvW returns path to executable if called with empty string.
        if commandline.strip() == "":
            return []
        if not strict:
            # not really a cl-arg, fallback on _process_common
            return py_arg_split(commandline, posix=posix, strict=strict)
        argvn = c_int()
        result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn))
        result_array_type = LPCWSTR * argvn.value
        result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))]
        retval = LocalFree(result_pointer)
        return result 
Example #5
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def Get(self, name, flags):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT),
                                       ctypes.POINTER(ctypes.c_long))

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'lFlags'),
                      (_Out_, 'pVal'),
                      (_Out_, 'plFlavor'),
                      )

        _Get = prototype(IWbemQualifierSet_Get_Idx,
                         'Get',
                         paramflags)
        _Get.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj, return_obj2 = _Get(self.this,
                                       name,
                                       flags
                                       )
        return return_obj, return_obj2 
Example #6
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 6 votes vote down vote up
def WlanDeleteProfile(hClientHandle, pInterfaceGuid, profileName):
    """
    DWORD WINAPI WlanDeleteProfile(
        _In_             HANDLE  hClientHandle,
        _In_       const GUID    *pInterfaceGuid,
        _In_             LPCWSTR strProfileName,
        _Reserved_       PVOID   pReserved
    );
    """
    func_ref = wlanapi.WlanDeleteProfile
    func_ref.argtypes = [HANDLE,
                         POINTER(GUID),
                         LPCWSTR,
                         c_void_p]
    func_ref.restype = DWORD
    result = func_ref(hClientHandle,
                      byref(pInterfaceGuid),
                      profileName,
                      None)
    if result != ERROR_SUCCESS:
        raise Exception("WlanDeleteProfile failed. error %d" % result, result)
    return result 
Example #7
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetValue(self, name, flags):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT))

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'lFlags'),
                      (_Out_, 'pValue'),
                      )

        _GetValue = prototype(IWbemContext_GetValue_Idx,
                              'GetValue',
                              paramflags)
        _GetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetValue(self.this,
                               name,
                               flags
                               )
        return return_obj 
Example #8
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def SetValue(self, name, flags, value):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT))

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'lFlags'),
                      (_In_, 'pValue'),
                      )

        _SetValue = prototype(IWbemContext_SetValue_Idx,
                              'SetValue',
                              paramflags)
        _SetValue.errcheck = winapi.RAISE_NON_ZERO_ERR
        _SetValue(self.this,
                  name,
                  flags,
                  ctypes.byref(value) if value else None
                  ) 
Example #9
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetMethodOrigin(self, method_name):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.POINTER(BSTR))

        paramflags = ((_In_, 'wszMethodName'),
                      (_Out_, 'pstrClassName'),
                      )

        _GetMethodOrigin = prototype(IWbemClassObject_GetMethodOrigin_Idx,
                                     'GetMethodOrigin',
                                     paramflags)
        _GetMethodOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetMethodOrigin(self.this,
                                      method_name
                                      )
        return_obj = winapi.convert_bstr_to_str(return_obj)
        return return_obj 
Example #10
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetMethodQualifierSet(self, method):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.POINTER(wintypes.LPVOID))

        paramflags = ((_In_, 'wszMethod'),
                      (_Out_, 'ppQualSet'),
                      )

        _GetMethodQualifierSet = prototype(IWbemClassObject_GetMethodQualifierSet_Idx,
                                           'GetMethodQualifierSet',
                                           paramflags)
        _GetMethodQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetMethodQualifierSet(self.this,
                                            method
                                            )
        try:
            return_obj = IWbemQualifierSet(return_obj)
        except WindowsError:
            return_obj = None
        return return_obj 
Example #11
Source File: DatabaseBuilder.py    From apiscout with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_aslr():
    # first check for a potentially rebased user32.dll
    from ctypes import windll
    from ctypes import wintypes
    check_dlls = ["user32.dll", "kernel32.dll", "ntdll.dll"]
    offsets = []
    is_aslr = False
    windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE
    windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
    windll.kernel32.GetModuleFileNameW.restype = wintypes.DWORD
    windll.kernel32.GetModuleFileNameW.argtypes = [wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD]
    for dll_name in check_dlls:
        h_module_base = windll.kernel32.GetModuleHandleW(dll_name)
        # next get the module's file path
        module_path = ctypes.create_unicode_buffer(255)
        windll.kernel32.GetModuleFileNameW(h_module_base, module_path, 255)
        # then the ImageBase from python.exe file
        pe = pefile.PE(module_path.value)
        pe_header_base_addr = pe.OPTIONAL_HEADER.ImageBase
        offsets.append(pe_header_base_addr - h_module_base)
    for dll_name, offset in zip(check_dlls, offsets):
        LOG.debug("Memory vs. File ImageBase offset (%s): 0x%x", dll_name, offset)
        is_aslr |= offset != 0
    return is_aslr 
Example #12
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetPropertyOrigin(self, name):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.POINTER(BSTR))

        paramflags = ((_In_, 'wszName'),
                      (_Out_, 'pstrClassName'),
                      )

        _GetPropertyOrigin = prototype(IWbemClassObject_GetPropertyOrigin_Idx,
                                       'GetPropertyOrigin',
                                       paramflags)
        _GetPropertyOrigin.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetPropertyOrigin(self.this,
                                        name
                                        )
        return_obj = winapi.convert_bstr_to_str(return_obj)
        return return_obj 
Example #13
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetPropertyQualifierSet(self, property_param):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.POINTER(wintypes.LPVOID))

        paramflags = ((_In_, 'wszProperty'),
                      (_Out_, 'ppQualSet'),
                      )

        _GetPropertyQualifierSet = prototype(IWbemClassObject_GetPropertyQualifierSet_Idx,
                                             'GetPropertyQualifierSet',
                                             paramflags)
        _GetPropertyQualifierSet.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetPropertyQualifierSet(self.this,
                                              property_param
                                              )
        try:
            return_obj = IWbemQualifierSet(return_obj)
        except WindowsError:
            return_obj = None
        return return_obj 
Example #14
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def GetNames(self, qualifier_name, flags, qualifier_val):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT),
                                       ctypes.POINTER(wintypes.LPVOID))

        paramflags = ((_In_, 'wszQualifierName'),
                      (_In_, 'lFlags'),
                      (_In_, 'pQualifierVal'),
                      (_Out_, 'pNames'),
                      )

        _GetNames = prototype(IWbemClassObject_GetNames_Idx,
                              'GetNames',
                              paramflags)
        _GetNames.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj = _GetNames(self.this,
                               qualifier_name,
                               flags,
                               ctypes.byref(qualifier_val) if qualifier_val else None
                               )
        return_obj = ctypes.cast(wintypes.LPVOID(return_obj), ctypes.POINTER(winapi.SAFEARRAY))
        return return_obj 
Example #15
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def Put(self, name, flags, val, type_param):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT),
                                       CIMTYPE)

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'lFlags'),
                      (_In_, 'pVal'),
                      (_In_, 'Type'),
                      )

        _Put = prototype(IWbemClassObject_Put_Idx,
                         'Put',
                         paramflags)
        _Put.errcheck = winapi.RAISE_NON_ZERO_ERR
        _Put(self.this,
             name,
             flags,
             ctypes.byref(val) if val else None,
             type_param
             ) 
Example #16
Source File: wmi.py    From cWMI with Apache License 2.0 6 votes vote down vote up
def Get(self, name, flags):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR,
                                       ctypes.c_long,
                                       ctypes.POINTER(winapi.VARIANT),
                                       ctypes.POINTER(CIMTYPE),
                                       ctypes.POINTER(ctypes.c_long))

        paramflags = ((_In_, 'wszName'),
                      (_In_, 'lFlags'),
                      (_Out_, 'pVal'),
                      (_Out_, 'pType'),
                      (_Out_, 'plFlavor'),
                      )

        _Get = prototype(IWbemClassObject_Get_Idx,
                         'Get',
                         paramflags)
        _Get.errcheck = winapi.RAISE_NON_ZERO_ERR
        return_obj, return_obj2, return_obj3 = _Get(self.this,
                                                    name,
                                                    flags
                                                    )
        return return_obj, return_obj2, return_obj3 
Example #17
Source File: msw_utils.py    From uniconvertor with GNU Affero General Public License v3.0 6 votes vote down vote up
def unicode_sys_argv():
    """Uses shell32.GetCommandLineArgvW to fix sys.argv as a list of
    unicode strings.
    """
    GetCommandLineW = ctypes.cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = wintypes.LPCWSTR
    cmd_line = GetCommandLineW()

    CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [wintypes.LPCWSTR,
                                   ctypes.POINTER(ctypes.c_int)]
    CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
    argc = ctypes.c_int(0)
    argv = CommandLineToArgvW(cmd_line, ctypes.byref(argc))

    if argc.value:
        rng = xrange(argc.value - len(sys.argv), argc.value)
        sys.argv = [argv[i] for i in rng] 
Example #18
Source File: win32compat.py    From py7zr with GNU Lesser General Public License v2.1 5 votes vote down vote up
def is_reparse_point(path: Union[str, pathlib.Path]) -> bool:
        GetFileAttributesW.argtypes = [LPCWSTR]
        GetFileAttributesW.restype = DWORD
        return _check_bit(GetFileAttributesW(str(path)), stat.FILE_ATTRIBUTE_REPARSE_POINT) 
Example #19
Source File: cmd.py    From pydu with MIT License 5 votes vote down vote up
def cmdline_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)
        raw_argv = CommandLineToArgvW(cmd, byref(argc))
        argnum = argc.value
        sysnum = len(sys.argv)
        argv = []
        if argnum > 0:
            # Remove Python executable and commands if present
            start = argnum - sysnum
            for i in range(start, argnum):
                argv.append(raw_argv[i])
        return argv 
Example #20
Source File: wget.py    From VKMusicDownloader with 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 #21
Source File: plat_win.py    From FileManager with MIT License 5 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    path = get_short_path_name(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(path, len(path)+2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(None, None, path, result) 
Example #22
Source File: plat_win.py    From Snu-Photo-Manager with GNU Lesser General Public License v3.0 5 votes vote down vote up
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    path = get_short_path_name(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(path, len(path)+2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(result, FormatError(result), path) 
Example #23
Source File: jbxapi.py    From jbxapi with MIT License 5 votes vote down vote up
def main(argv=None):
    # Workaround for a bug in Python 2.7 where sys.argv arguments are converted to ASCII and
    # non-ascii characters are replaced with '?'.
    #
    # https://bugs.python.org/issue2128
    # https://stackoverflow.com/q/846850/
    if sys.version_info[0] == 2 and sys.platform.startswith('win32'):
        def win32_unicode_argv():
            """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode strings.
            """

            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))
            if argc.value > 0:
                # Remove Python executable and commands if present
                start = argc.value - len(sys.argv)
                return [argv[i] for i in
                        xrange(start, argc.value)]

        sys.argv = win32_unicode_argv()

    cli(argv if argv is not None else sys.argv[1:]) 
Example #24
Source File: t-less_download.py    From patch_linemod with 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 #25
Source File: install_package.py    From r-bridge-install with Apache License 2.0 5 votes vote down vote up
def bridge_running(product):
    """ Check if the R ArcGIS bridge is running. Installation wil fail
    if the DLL is currently loaded."""
    running = False
    # check for the correct DLL
    if product == 'Pro':
        proxy_name = "rarcproxy_pro.dll"
    else:
        proxy_name = "rarcproxy.dll"
    kdll.GetModuleHandleW.restype = wintypes.HMODULE
    kdll.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
    dll_handle = kdll.GetModuleHandleW(proxy_name)  # memory address of DLL
    if dll_handle is not None:
        running = True
    return running 
Example #26
Source File: generic.py    From quantipy with MIT License 5 votes vote down vote up
def wide2utf8(self, fn):
        """Take a unicode file name string and encode it to a multibyte string
        that Windows can use to represent file names (CP65001, UTF-8)
        http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130"""

        from ctypes import wintypes

        _CP_UTF8 = 65001
        _CP_ACP = 0  # ANSI
        _LPBOOL = POINTER(c_long)

        _wideCharToMultiByte = windll.kernel32.WideCharToMultiByte
        _wideCharToMultiByte.restype = c_int
        _wideCharToMultiByte.argtypes = [wintypes.UINT, wintypes.DWORD,
                                         wintypes.LPCWSTR, c_int,
                                         wintypes.LPSTR, c_int,
                                         wintypes.LPCSTR, _LPBOOL]
        codePage = _CP_UTF8
        dwFlags = 0
        lpWideCharStr = fn
        cchWideChar = len(fn)
        lpMultiByteStr = None
        cbMultiByte = 0  # zero requests size
        lpDefaultChar = None
        lpUsedDefaultChar = None

        # get size
        mbcssize = _wideCharToMultiByte(
        codePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr,
        cbMultiByte, lpDefaultChar, lpUsedDefaultChar)
        if mbcssize <= 0:
            raise WinError(mbcssize)
        lpMultiByteStr = create_string_buffer(mbcssize)

        # convert
        retcode = _wideCharToMultiByte(
        codePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr,
        mbcssize, lpDefaultChar, lpUsedDefaultChar)
        if retcode <= 0:
            raise WinError(retcode)
        return lpMultiByteStr.value 
Example #27
Source File: hotkeys.py    From PyPipboyApp with GNU General Public License v3.0 5 votes vote down vote up
def listener():
    try:
        #print("LLHookey: in listener")
        from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref
        import atexit
        event_types = {0x100: 'key down', #WM_KeyDown for normal keys
           0x101: 'key up', #WM_KeyUp for normal keys
           0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key.
           0x105: 'key up', # WM_SYSKEYUP, used for Alt key.
          }
        def low_level_handler(nCode, wParam, lParam):
            
            event = KeyEvent(event_types[wParam], lParam[0], lParam[1],
                              lParam[2] == 32, lParam[3])
            for h in handlers:
                h(event)
            #Be nice, return next hook
            return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam)
    
        
        # Our low level handler signature.
        CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
        # Convert the Python handler into C pointer.
        pointer = CMPFUNC(low_level_handler)
        #Added 4-18-15 for move to ctypes:
        windll.kernel32.GetModuleHandleW.restype = wintypes.HMODULE
        windll.kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
        # Hook both key up and key down events for common keys (non-system).
        hook_id = windll.user32.SetWindowsHookExA(0x00D, pointer,
                                                 windll.kernel32.GetModuleHandleW(None), 0)
    
        # Register to remove the hook when the interpreter exits.
        atexit.register(windll.user32.UnhookWindowsHookEx, hook_id)
        msg = windll.user32.GetMessageW(None, 0, 0,0)
        windll.user32.TranslateMessage(byref(msg))
        windll.user32.DispatchMessageW(byref(msg))
    except:
        traceback.print_exc(file=sys.stdout) 
Example #28
Source File: Win32NativeWifiApi.py    From win32wifi with GNU General Public License v3.0 5 votes vote down vote up
def WlanGetProfile(hClientHandle, pInterfaceGuid, profileName):
    """
        The WlanGetProfile function retrieves all information about a specified
        wireless profile.

        DWORD WINAPI WlanGetProfile(
            _In_         HANDLE hClientHandle,
            _In_         const GUID *pInterfaceGuid,
            _In_         LPCWSTR strProfileName,
            _Reserved_   PVOID pReserved,
            _Out_        LPWSTR *pstrProfileXml,
            _Inout_opt_  DWORD *pdwFlags,
            _Out_opt_    PDWORD pdwGrantedAccess
        );
    """
    func_ref = wlanapi.WlanGetProfile
    func_ref.argtypes = [HANDLE,
                         POINTER(GUID),
                         LPCWSTR,
                         c_void_p,
                         POINTER(LPWSTR),
                         POINTER(DWORD),
                         POINTER(DWORD)]
    func_ref.restype = DWORD
    pdw_granted_access = DWORD()
    xml = LPWSTR()
    flags = DWORD(WLAN_PROFILE_GET_PLAINTEXT_KEY)
    result = func_ref(hClientHandle,
                      byref(pInterfaceGuid),
                      profileName,
                      None,
                      byref(xml),
                      byref(flags),
                      byref(pdw_granted_access))
    if result != ERROR_SUCCESS:
        raise Exception("WlanGetProfile failed.")
    return xml 
Example #29
Source File: win32_unicode_argv.py    From rclonesync-V2 with MIT License 5 votes vote down vote up
def win32_unicode_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))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i] for i in
                xrange(start, argc.value)] 
Example #30
Source File: wmi.py    From cWMI with Apache License 2.0 5 votes vote down vote up
def DeleteMethod(self, name):
        prototype = ctypes.WINFUNCTYPE(HRESULT,
                                       wintypes.LPCWSTR)

        paramflags = ((_In_, 'wszName'),
                      )

        _DeleteMethod = prototype(IWbemClassObject_DeleteMethod_Idx,
                                  'DeleteMethod',
                                  paramflags)
        _DeleteMethod.errcheck = winapi.RAISE_NON_ZERO_ERR
        _DeleteMethod(self.this,
                      name
                      )