Python ctypes 模块,c_wchar_p() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ctypes.c_wchar_p()

项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _copyWindows(text):
    GMEM_DDESHARE = 0x2000
    CF_UNICODETEXT = 13
    d = ctypes.windll  # cdll expects 4 more bytes in user32.OpenClipboard(0)
    if not isinstance(text, text_type):
        text = text.decode('mbcs')

    d.user32.OpenClipboard(0)

    d.user32.EmptyClipboard()
    hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE,
                                 len(text.encode('utf-16-le')) + 2)
    pchData = d.kernel32.GlobalLock(hCd)
    ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
    d.kernel32.GlobalUnlock(hCd)
    d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
    d.user32.CloseClipboard()
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def query_link(linkpath):
    utf16_len = len(linkpath) * 2
    obj_attr = OBJECT_ATTRIBUTES()
    obj_attr.Length = ctypes.sizeof(obj_attr)
    obj_attr.RootDirectory = 0
    obj_attr.ObjectName = pointer(LSA_UNICODE_STRING(utf16_len, utf16_len, linkpath))
    obj_attr.Attributes = OBJ_CASE_INSENSITIVE
    obj_attr.SecurityDescriptor = 0
    obj_attr.SecurityQualityOfService = 0

    res = HANDLE()
    x = winproxy.NtOpenSymbolicLinkObject(res, DIRECTORY_QUERY | READ_CONTROL , obj_attr)
    v = LSA_UNICODE_STRING(0x1000, 0x1000, ctypes.cast(ctypes.c_buffer(0x1000), ctypes.c_wchar_p))
    s = ULONG()
    winproxy.NtQuerySymbolicLinkObject(res, v, s)
    return v.Buffer
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def hook_callback(self, *args):
        adapted_args = []
        for value, type in zip(args, self.original_types[1:]):
            if type == ctypes.c_wchar_p:
                adapted_args.append(ctypes.c_wchar_p(value))
            elif type == ctypes.c_char_p:
                adapted_args.append(ctypes.c_char_p((value)))
            else:
                adapted_args.append(value)

        def real_function(*args):
            if args == ():
                args = adapted_args
            return self.realfunction(*args)
        return self.callback(*adapted_args, real_function=real_function)

    # Use this tricks to prevent garbage collection of hook ?
    #def __del__(self):
    #    pass


## New simple hook API based on winproxy
项目:zoocore    作者:dsparrow27    | 项目源码 | 文件源码
def symlink_ms(source, linkname):
        """Python 2 doesn't have os.symlink on windows so we do it ourselfs

        :param source: sourceFile
        :type source: str
        :param linkname: symlink path
        :type linkname: str
        :raises: WindowsError, raises when it fails to create the symlink if the user permissions
         are incorrect
        """
        import ctypes
        csl = ctypes.windll.kernel32.CreateSymbolicLinkW
        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
        csl.restype = ctypes.c_ubyte
        flags = 1 if os.path.isdir(source) else 0
        try:
            if csl(linkname, source.replace('/', '\\'), flags) == 0:
                raise ctypes.WinError()
        except WindowsError:
            raise WindowsError("Failed to create symbolicLink due to user permissions")
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def getFreeSpace(self):
        free_space = 0
        if "statvfs" in dir(os):  # Unix
            statvfs = os.statvfs(config.data_dir)
            free_space = statvfs.f_frsize * statvfs.f_bavail
        else:  # Windows
            try:
                import ctypes
                free_space_pointer = ctypes.c_ulonglong(0)
                ctypes.windll.kernel32.GetDiskFreeSpaceExW(
                    ctypes.c_wchar_p(config.data_dir), None, None, ctypes.pointer(free_space_pointer)
                )
                free_space = free_space_pointer.value
            except Exception, err:
                self.log.debug("GetFreeSpace error: %s" % err)
        return free_space
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def _get_long_path_name(path):
        """Get a long path name (expand ~) on Windows using ctypes.

        Examples
        --------

        >>> get_long_path_name('c:\\docume~1')
        'c:\\\\Documents and Settings'

        """
        try:
            import ctypes
        except ImportError:
            raise ImportError('you need to have ctypes installed for this to work')
        _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
        _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
            ctypes.c_uint ]

        buf = ctypes.create_unicode_buffer(260)
        rv = _GetLongPathName(path, buf, 260)
        if rv == 0 or rv > 260:
            return path
        else:
            return buf.value
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def get_free_space(path=settings.KOLIBRI_HOME):
    if sys.platform.startswith('win'):
        import ctypes

        free = ctypes.c_ulonglong(0)
        check = ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(free))
        if check == 0:
            raise ctypes.winError()
        result = free.value
    else:
        st = os.statvfs(path)
        result = st.f_bavail * st.f_frsize

    return result


# Utility functions for pinging or killing PIDs
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def fsbsize(path):
    """
    Get optimal file system buffer size (in bytes) for I/O calls
    """
    path = encode(path)

    if os.name == "nt":
        import ctypes

        drive = "%s\\" % os.path.splitdrive(path)[0]
        cluster_sectors, sector_size = ctypes.c_longlong(0)

        ctypes.windll.kernel32.GetDiskFreeSpaceW(ctypes.c_wchar_p(drive),
                                                 ctypes.pointer(
                                                     cluster_sectors),
                                                 ctypes.pointer(sector_size),
                                                 None,
                                                 None)
        return cluster_sectors * sector_size

    else:
        return os.statvfs(path).f_frsize
项目:cuckoo-headless    作者:evandowning    | 项目源码 | 文件源码
def rename_regkey(skey, ssubkey, dsubkey):
    """Rename an entire tree of values in the registry.
    Function by Thorsten Sick."""
    res_handle = HANDLE()
    options = DWORD(0)
    res = RegOpenKeyExW(
        skey, ssubkey, options, _winreg.KEY_ALL_ACCESS, byref(res_handle)
    )
    if not res:
        bsize = c_ushort(len(dsubkey) * 2)
        us = UNICODE_STRING()
        us.Buffer = c_wchar_p(dsubkey)
        us.Length = bsize
        us.MaximumLength = bsize

        res = NtRenameKey(res_handle, pointer(us))
        if res:
            log.warning("Error renaming %s\\%s to %s (0x%x)",
                        skey, ssubkey, dsubkey, res % 2**32)

    if res_handle:
        RegCloseKey(res_handle)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _get_long_path_name(path):
        """Get a long path name (expand ~) on Windows using ctypes.

        Examples
        --------

        >>> get_long_path_name('c:\\docume~1')
        u'c:\\\\Documents and Settings'

        """
        try:
            import ctypes
        except ImportError:
            raise ImportError('you need to have ctypes installed for this to work')
        _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
        _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
            ctypes.c_uint ]

        buf = ctypes.create_unicode_buffer(260)
        rv = _GetLongPathName(path, buf, 260)
        if rv == 0 or rv > 260:
            return path
        else:
            return buf.value
项目:pipenv    作者:pypa    | 项目源码 | 文件源码
def replace(src, dst):
        # argument names match stdlib docs, docstring below
        try:
            # ReplaceFile fails if the dest file does not exist, so
            # first try to rename it into position
            os.rename(src, dst)
            return
        except WindowsError as we:
            if we.errno == errno.EEXIST:
                pass  # continue with the ReplaceFile logic below
            else:
                raise

        src = path_to_unicode(src)
        dst = path_to_unicode(dst)
        res = _ReplaceFile(c_wchar_p(dst), c_wchar_p(src),
                           None, 0, None, None)
        if not res:
            raise OSError('failed to replace %r with %r' % (dst, src))
        return
项目:fuse-3ds    作者:ihaveamac    | 项目源码 | 文件源码
def statfs(self, path):
        if common.windows:
            lpSectorsPerCluster = ctypes.c_ulonglong(0)
            lpBytesPerSector = ctypes.c_ulonglong(0)
            lpNumberOfFreeClusters = ctypes.c_ulonglong(0)
            lpTotalNumberOfClusters = ctypes.c_ulonglong(0)
            ret = windll.kernel32.GetDiskFreeSpaceW(ctypes.c_wchar_p(path), ctypes.pointer(lpSectorsPerCluster), ctypes.pointer(lpBytesPerSector), ctypes.pointer(lpNumberOfFreeClusters), ctypes.pointer(lpTotalNumberOfClusters))
            if not ret:
                raise WindowsError
            free_blocks = lpNumberOfFreeClusters.value * lpSectorsPerCluster.value
            result = {'f_bavail': free_blocks,
                      'f_bfree': free_blocks,
                      'f_bsize': lpBytesPerSector.value,
                      'f_frsize': lpBytesPerSector.value,
                      'f_blocks': lpTotalNumberOfClusters.value * lpSectorsPerCluster.value,
                      'f_namemax': wintypes.MAX_PATH}
            return result
        else:
            stv = os.statvfs(path)
            # f_flag causes python interpreter crashes in some cases. i don't get it.
            return dict((key, getattr(stv, key)) for key in ('f_bavail', 'f_bfree', 'f_blocks', 'f_bsize', 'f_favail',
                                                             'f_ffree', 'f_files', 'f_frsize', 'f_namemax'))
项目:core    作者:getavalon    | 项目源码 | 文件源码
def _create_windows(source, destination, link_type):
    """Creates hardlink at destination from source in Windows."""

    if link_type == HARDLINK:
        import ctypes
        from ctypes.wintypes import BOOL
        CreateHardLink = ctypes.windll.kernel32.CreateHardLinkW
        CreateHardLink.argtypes = [
            ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_void_p
        ]
        CreateHardLink.restype = BOOL

        res = CreateHardLink(destination, source, None)
        if res == 0:
            raise ctypes.WinError()
    else:
        raise NotImplementedError("Link type unrecognized.")
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def start(self):
    """Start watching the directory for changes."""
    self._directory_handle = ctypes.windll.kernel32.CreateFileW(
        ctypes.c_wchar_p(self._directory),
        ctypes.c_ulong(_FILE_LIST_DIRECTORY),
        ctypes.c_ulong(_FILE_SHARE_READ |
                       _FILE_SHARE_WRITE),
        None,
        ctypes.c_ulong(_OPEN_EXISTING),
        # required to monitor changes.
        ctypes.c_ulong(_FILE_FLAG_BACKUP_SEMANTICS),
        None)
    if self._directory_handle == _INVALID_HANDLE_VALUE:
      raise ctypes.WinError()
    self._thread = threading.Thread(
        target=self._monitor, name='Win32 File Watcher')
    self._thread.start()
项目:transmission_scripts    作者:leighmacdonald    | 项目源码 | 文件源码
def get_free_space(dir_name):
    """Get free space in bytes for the path provided

    :param dir_name:
    :return:
    """
    if platform.system() == 'Windows':
        import ctypes
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(
            ctypes.c_wchar_p(dir_name), None, None, ctypes.pointer(free_bytes)
        )
        return free_bytes.value
    else:
        st = os.statvfs(dir_name)
        return st.f_bavail * st.f_frsize
项目:wger-lycan-clan    作者:andela    | 项目源码 | 文件源码
def win32_get_app_data_path(*args):
    shell32 = ctypes.WinDLL("shell32.dll")
    SHGetFolderPath = shell32.SHGetFolderPathW
    SHGetFolderPath.argtypes = (
        ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32,
        ctypes.c_wchar_p)
    SHGetFolderPath.restype = ctypes.c_uint32

    CSIDL_LOCAL_APPDATA = 0x001c
    MAX_PATH = 260

    buf = ctypes.create_unicode_buffer(MAX_PATH)
    res = SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, buf)
    if res != 0:
        raise Exception("Could not deterime APPDATA path")

    return os.path.join(buf.value, *args)
项目:pyload-plugins    作者:pyload    | 项目源码 | 文件源码
def fsbsize(path):
    """
    Get optimal file system buffer size (in bytes) for I/O calls
    """
    path = encode(path)

    if os.name == "nt":
        import ctypes

        drive = "%s\\" % os.path.splitdrive(path)[0]
        cluster_sectors, sector_size = ctypes.c_longlong(0)

        ctypes.windll.kernel32.GetDiskFreeSpaceW(ctypes.c_wchar_p(drive),
                                                 ctypes.pointer(
                                                     cluster_sectors),
                                                 ctypes.pointer(sector_size),
                                                 None,
                                                 None)
        return cluster_sectors * sector_size

    else:
        return os.statvfs(path).f_frsize
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def _get_long_path_name(path):
        """Get a long path name (expand ~) on Windows using ctypes.

        Examples
        --------

        >>> get_long_path_name('c:\\docume~1')
        u'c:\\\\Documents and Settings'

        """
        try:
            import ctypes
        except ImportError:
            raise ImportError('you need to have ctypes installed for this to work')
        _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
        _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
            ctypes.c_uint ]

        buf = ctypes.create_unicode_buffer(260)
        rv = _GetLongPathName(path, buf, 260)
        if rv == 0 or rv > 260:
            return path
        else:
            return buf.value
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def _get_long_path_name(path):
        """Get a long path name (expand ~) on Windows using ctypes.

        Examples
        --------

        >>> get_long_path_name('c:\\docume~1')
        'c:\\\\Documents and Settings'

        """
        try:
            import ctypes
        except ImportError:
            raise ImportError('you need to have ctypes installed for this to work')
        _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
        _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
            ctypes.c_uint ]

        buf = ctypes.create_unicode_buffer(260)
        rv = _GetLongPathName(path, buf, 260)
        if rv == 0 or rv > 260:
            return path
        else:
            return buf.value
项目:lib9    作者:Jumpscale    | 项目源码 | 文件源码
def clipboardSet(self, text):
        self.initKernel()
        CF_UNICODETEXT = 13
        GHND = 66
        if text is None:
            return

        if isinstance(text, type('')):
            text = str(text, 'mbcs')
        bufferSize = (len(text) + 1) * 2
        hGlobalMem = ctypes.windll.kernel32.GlobalAlloc(ctypes.c_int(GHND), ctypes.c_int(bufferSize))
        ctypes.windll.kernel32.GlobalLock.restype = ctypes.c_void_p
        lpGlobalMem = ctypes.windll.kernel32.GlobalLock(ctypes.c_int(hGlobalMem))
        ctypes.cdll.msvcrt.memcpy(lpGlobalMem, ctypes.c_wchar_p(text), ctypes.c_int(bufferSize))
        ctypes.windll.kernel32.GlobalUnlock(ctypes.c_int(hGlobalMem))
        if ctypes.windll.user32.OpenClipboard(0):
            ctypes.windll.user32.EmptyClipboard()
            ctypes.windll.user32.SetClipboardData(ctypes.c_int(CF_UNICODETEXT), ctypes.c_int(hGlobalMem))
            ctypes.windll.user32.CloseClipboard()
项目:senf    作者:quodlibet    | 项目源码 | 文件源码
def test_python_handling_broken_utf16():
    # Create a file with an invalid utf-16 name.
    # Mainly to see how Python handles it

    tmp = mkdtemp()
    try:
        path = os.path.join(tmp, "foo")
        with open(path, "wb") as h:
            h.write(b"content")
        assert "foo" in os.listdir(tmp)

        if os.name == "nt":
            faulty = (path.encode("utf-16-le") + b"=\xd8\x01\xde" +
                      b"=\xd8-\x00\x01\xde")
            buf = ctypes.create_string_buffer(faulty + b"\x00\x00")

            if winapi.MoveFileW(path, ctypes.cast(buf, ctypes.c_wchar_p)) == 0:
                raise ctypes.WinError()
            assert "foo" not in os.listdir(tmp)

            newpath = os.path.join(tmp, os.listdir(tmp)[0])
            if not is_wine:  # this is broken on wine..
                assert newpath.encode("utf-16-le", _surrogatepass) == faulty

            with open(newpath, "rb") as h:
                assert h.read() == b"content"
    finally:
        shutil.rmtree(tmp)
项目:PythonForWindows    作者:hakril    | 项目源码 | 文件源码
def transform_arguments(self, types):
        res = []
        for type in types:
            if type in (ctypes.c_wchar_p, ctypes.c_char_p):
                res.append(ctypes.c_void_p)
            else:
                res.append(type)
        return res
项目:spread-knowledge-repository    作者:danieldev13    | 项目源码 | 文件源码
def _get_known_folder_path(uuidstr):
        pathptr = ctypes.c_wchar_p()
        guid = GUID(uuidstr)
        if SHGetKnownFolderPath(ctypes.byref(guid), 0, 0, ctypes.byref(pathptr)):
            raise ctypes.WinError()
        return pathptr.value
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def setUpClass(cls):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        cls.wcslen = dll.my_wcslen
        cls.wcslen.argtypes = [ctypes.c_wchar_p]
项目:SDK    作者:Keypirinha    | 项目源码 | 文件源码
def get_known_folder_path(known_folder_guidstr):
    guid = GUID(known_folder_guidstr)
    path_ptr = ct.c_wchar_p()
    res = shell32.SHGetKnownFolderPath(ct.byref(guid), 0, None, ct.byref(path_ptr))
    if res:
        raise OSError(0, "SHGetKnownFolderPath('{}') failed (code {})".format(known_folder_guidstr, res), None, res)
    return path_ptr.value
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list
项目:pythonVSCode    作者:DonJayamanne    | 项目源码 | 文件源码
def _command_line_to_args_list(cmdline):
    """splits a string into a list using Windows command line syntax."""
    args_list = []

    if cmdline and cmdline.strip():
        from ctypes import c_int, c_voidp, c_wchar_p
        from ctypes import byref, POINTER, WinDLL

        clta = WinDLL('shell32').CommandLineToArgvW
        clta.argtypes = [c_wchar_p, POINTER(c_int)]
        clta.restype = POINTER(c_wchar_p)

        lf = WinDLL('kernel32').LocalFree
        lf.argtypes = [c_voidp]

        pNumArgs = c_int()
        r = clta(cmdline, byref(pNumArgs))
        if r:
            for index in range(0, pNumArgs.value):
                if sys.hexversion >= 0x030000F0:
                    argval = r[index]
                else:
                    argval = r[index].encode('ascii', 'replace')
                args_list.append(argval)
            lf(r)
        else:
            sys.stderr.write('Error parsing script arguments:\n')
            sys.stderr.write(cmdline + '\n')

    return args_list
项目:Qyoutube-dl    作者:lzambella    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
            # c_wchar_p() might not be necessary if `message` is
            # already of type unicode()
            ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:youtube_downloader    作者:aksinghdce    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if compat_os_name == 'nt':
            if ctypes.windll.kernel32.GetConsoleWindow():
                # c_wchar_p() might not be necessary if `message` is
                # already of type unicode()
                ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:optimalvibes    作者:littlemika    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if compat_os_name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
            # c_wchar_p() might not be necessary if `message` is
            # already of type unicode()
            ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:tvalacarta    作者:tvalacarta    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if compat_os_name == 'nt':
            if ctypes.windll.kernel32.GetConsoleWindow():
                # c_wchar_p() might not be necessary if `message` is
                # already of type unicode()
                ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:pysetupdi    作者:gwangyi    | 项目源码 | 文件源码
def __str__(self):
        s = ctypes.c_wchar_p()
        ret = _ole32.StringFromCLSID(ctypes.byref(self), ctypes.byref(s))
        if ret < 0:
            err_no = ctypes.GetLastError()
            raise WindowsError(err_no, ctypes.FormatError(err_no))
        ret = str(s.value)
        _ole32.CoTaskMemFree(s)
        return ret
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_wcslen(self):
            dll = ctypes.CDLL(_ctypes_test.__file__)
            wcslen = dll.my_wcslen
            wcslen.argtypes = [ctypes.c_wchar_p]

            self.assertEqual(wcslen("abc"), 3)
            self.assertEqual(wcslen("ab\u2070"), 3)
            self.assertRaises(ctypes.ArgumentError, wcslen, b"ab\xe4")
项目:Moderat    作者:Swordf1sh    | 项目源码 | 文件源码
def get_username():
    advapi32 = ctypes.windll.advapi32
    GetUserNameW = advapi32.GetUserNameW
    GetUserNameW.argtypes = [ctypes.c_wchar_p, ctypes.POINTER(ctypes.c_uint)]
    GetUserNameW.restype = ctypes.c_uint

    def GetUserName():
        buffer = ctypes.create_unicode_buffer(2)
        size = ctypes.c_uint(len(buffer))
        while not GetUserNameW(buffer, ctypes.byref(size)):
            buffer = ctypes.create_unicode_buffer(len(buffer) * 2)
            size.value = len(buffer)
        return buffer.value

    return GetUserName()
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def setUpClass(cls):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        cls.wcslen = dll.my_wcslen
        cls.wcslen.argtypes = [ctypes.c_wchar_p]
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def setUpClass(cls):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        cls.wcslen = dll.my_wcslen
        cls.wcslen.argtypes = [ctypes.c_wchar_p]
项目:kodi-plugin.video.ted-talks-chinese    作者:daineseh    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if compat_os_name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
            # c_wchar_p() might not be necessary if `message` is
            # already of type unicode()
            ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def freeSpace(folder):
    if os.name == "nt":
        import ctypes

        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value
    else:
        from os import statvfs

        s = statvfs(folder)
        return s.f_bsize * s.f_bavail
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def free_space(folder):
    if os.name == "nt":
        import ctypes

        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder),
                                                   None,
                                                   None,
                                                   ctypes.pointer(free_bytes))
        return free_bytes.value

    else:
        s = os.statvfs(folder)
        return s.f_frsize * s.f_bavail
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def setUpClass(cls):
        dll = ctypes.CDLL(_ctypes_test.__file__)
        cls.wcslen = dll.my_wcslen
        cls.wcslen.argtypes = [ctypes.c_wchar_p]
项目:cuckoo-headless    作者:evandowning    | 项目源码 | 文件源码
def shortpath(self, path):
        """Returns the shortpath for a file.

        As Python 2.7 does not support passing along unicode strings in
        subprocess.Popen() and alike this will have to do. See also:
        http://stackoverflow.com/questions/2595448/unicode-filename-to-python-subprocess-call
        """
        KERNEL32.GetShortPathNameW.restype = c_uint
        KERNEL32.GetShortPathNameW.argtypes = c_wchar_p, c_wchar_p, c_uint

        buf = create_unicode_buffer(0x8000)
        KERNEL32.GetShortPathNameW(path, buf, len(buf))
        return buf.value
项目:splunk_shells    作者:TBGSecurity    | 项目源码 | 文件源码
def _core_machine_id(self, request, response):
                serial = ''
                machine_name = platform.uname()[1]
                if has_windll:
                    from ctypes import wintypes

                    k32 = ctypes.windll.kernel32
                    sys_dir = ctypes.create_unicode_buffer(260)
                    if not k32.GetSystemDirectoryW(ctypes.byref(sys_dir), 260):
                        return ERROR_FAILURE_WINDOWS

                    vol_buf = ctypes.create_unicode_buffer(260)
                    fs_buf = ctypes.create_unicode_buffer(260)
                    serial_num = wintypes.DWORD(0)

                    if not k32.GetVolumeInformationW(ctypes.c_wchar_p(sys_dir.value[:3]),
                                                     vol_buf, ctypes.sizeof(vol_buf), ctypes.byref(serial_num), None,
                                                     None, fs_buf, ctypes.sizeof(fs_buf)):
                        return ERROR_FAILURE_WINDOWS
                    serial_num = serial_num.value
                    serial = "{0:04x}-{1:04x}".format((serial_num >> 16) & 0xFFFF, serial_num & 0xFFFF)
                else:
                    serial = get_hdd_label()

                response += tlv_pack(TLV_TYPE_MACHINE_ID, "%s:%s" % (serial, machine_name))
                return ERROR_SUCCESS, response
项目:splunk_shells    作者:TBGSecurity    | 项目源码 | 文件源码
def _core_machine_id(self, request, response):
                serial = ''
                machine_name = platform.uname()[1]
                if has_windll:
                    from ctypes import wintypes

                    k32 = ctypes.windll.kernel32
                    sys_dir = ctypes.create_unicode_buffer(260)
                    if not k32.GetSystemDirectoryW(ctypes.byref(sys_dir), 260):
                        return ERROR_FAILURE_WINDOWS

                    vol_buf = ctypes.create_unicode_buffer(260)
                    fs_buf = ctypes.create_unicode_buffer(260)
                    serial_num = wintypes.DWORD(0)

                    if not k32.GetVolumeInformationW(ctypes.c_wchar_p(sys_dir.value[:3]),
                                                     vol_buf, ctypes.sizeof(vol_buf), ctypes.byref(serial_num), None,
                                                     None, fs_buf, ctypes.sizeof(fs_buf)):
                        return ERROR_FAILURE_WINDOWS
                    serial_num = serial_num.value
                    serial = "{0:04x}-{1:04x}".format((serial_num >> 16) & 0xFFFF, serial_num & 0xFFFF)
                else:
                    serial = get_hdd_label()

                response += tlv_pack(TLV_TYPE_MACHINE_ID, "%s:%s" % (serial, machine_name))
                return ERROR_SUCCESS, response
项目:splunk_shells    作者:TBGSecurity    | 项目源码 | 文件源码
def _core_machine_id(self, request, response):
                serial = ''
                machine_name = platform.uname()[1]
                if has_windll:
                    from ctypes import wintypes

                    k32 = ctypes.windll.kernel32
                    sys_dir = ctypes.create_unicode_buffer(260)
                    if not k32.GetSystemDirectoryW(ctypes.byref(sys_dir), 260):
                        return ERROR_FAILURE_WINDOWS

                    vol_buf = ctypes.create_unicode_buffer(260)
                    fs_buf = ctypes.create_unicode_buffer(260)
                    serial_num = wintypes.DWORD(0)

                    if not k32.GetVolumeInformationW(ctypes.c_wchar_p(sys_dir.value[:3]),
                                                     vol_buf, ctypes.sizeof(vol_buf), ctypes.byref(serial_num), None,
                                                     None, fs_buf, ctypes.sizeof(fs_buf)):
                        return ERROR_FAILURE_WINDOWS
                    serial_num = serial_num.value
                    serial = "{0:04x}-{1:04x}".format((serial_num >> 16) & 0xFFFF, serial_num & 0xFFFF)
                else:
                    serial = get_hdd_label()

                response += tlv_pack(TLV_TYPE_MACHINE_ID, "%s:%s" % (serial, machine_name))
                return ERROR_SUCCESS, response
项目:bonsu    作者:bonsudev    | 项目源码 | 文件源码
def FreeSpace(path):
    if platform.startswith('win'):
        free = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path), None, None, ctypes.pointer(free))
        return free.value
    else:
        stat = os.statvfs(path)
        free = stat.f_frsize * stat.f_bavail
        return free
项目:wptagent    作者:WPO-Foundation    | 项目源码 | 文件源码
def get_free_disk_space():
    """Return the number of bytes free on the given disk in Gigabytes (floating)"""
    path = os.path.dirname(os.path.realpath(__file__))
    if platform.system() == 'Windows':
        import ctypes
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(path),
                                                   None, None, ctypes.pointer(free_bytes))
        return float(free_bytes.value / 1024 / 1024) / 1024.0
    else:
        stat = os.statvfs(path)
        return float(stat.f_bavail * stat.f_frsize / 1024 / 1024) / 1024.0
# pylint: enable=E1101
项目:GUIYoutube    作者:coltking    | 项目源码 | 文件源码
def to_console_title(self, message):
        if not self.params.get('consoletitle', False):
            return
        if compat_os_name == 'nt':
            if ctypes.windll.kernel32.GetConsoleWindow():
                # c_wchar_p() might not be necessary if `message` is
                # already of type unicode()
                ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
        elif 'TERM' in os.environ:
            self._write_string('\033]0;%s\007' % message, self._screen_file)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def _cast_signature_pointers_to_void(self, signature):
        c_void_p  = ctypes.c_void_p
        c_char_p  = ctypes.c_char_p
        c_wchar_p = ctypes.c_wchar_p
        _Pointer  = ctypes._Pointer
        cast      = ctypes.cast
        for i in compat.xrange(len(signature)):
            t = signature[i]
            if t is not c_void_p and (issubclass(t, _Pointer) \
                                            or t in [c_char_p, c_wchar_p]):
                signature[i] = cast(t, c_void_p)
项目:MFCRecorder    作者:beaston02    | 项目源码 | 文件源码
def _get_free_diskspace(self):
        '''https://stackoverflow.com/questions/51658/cross-platform-space-remaining-on-volume-using-python'''
        if platform.system() == 'Windows':
            free_bytes = ctypes.c_ulonglong(0)
            ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(self.settings.save_directory), None, None, ctypes.pointer(free_bytes))
            return free_bytes.value / 1024 / 1024
        st = os.statvfs(self.settings.save_directory)
        return st.f_bavail * st.f_frsize / 1024 / 1024 / 1024
项目:automatic-repo    作者:WZQ1397    | 项目源码 | 文件源码
def get_free_space_mb(folder):
    """ Return folder/drive free space (in bytes)
    """
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value/1024/1024/1024
    else:
        st = os.statvfs(folder)
        return st.f_bavail * st.f_frsize/1024/1024