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()
python类c_wchar_p()的实例源码
clipboard.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
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
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
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")
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
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
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
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
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)
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
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
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'))
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.")
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()
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
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)
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
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
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
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()
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)
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
operating_system_helper.py 文件源码
项目:spread-knowledge-repository
作者: danieldev13
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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
def setUpClass(cls):
dll = ctypes.CDLL(_ctypes_test.__file__)
cls.wcslen = dll.my_wcslen
cls.wcslen.argtypes = [ctypes.c_wchar_p]
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
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
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
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)
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)
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)