def get_ctypes_strsignal():
"""Strategy 1: If the C library exposes strsignal(), use it."""
import signal
import ctypes
import ctypes.util
libc = ctypes.CDLL(ctypes.util.find_library("c"))
strsignal_proto = ctypes.CFUNCTYPE(ctypes.c_char_p,
ctypes.c_int)
strsignal_c = strsignal_proto(("strsignal", libc), ((1,),))
NSIG = signal.NSIG
def strsignal_ctypes_wrapper(signo):
# The behavior of the C library strsignal() is unspecified if
# called with an out-of-range argument. Range-check on entry
# _and_ NULL-check on exit.
if 0 <= signo < NSIG:
s = strsignal_c(signo)
if s:
return s.decode("utf-8")
return "Unknown signal "+str(signo)
return strsignal_ctypes_wrapper
python类util()的实例源码
def openLibrary():
import ctypes
import ctypes.util
try:
if sys.platform.startswith("win"):
dll_path = "src/lib/opensslVerify/libeay32.dll"
elif sys.platform == "cygwin":
dll_path = "/bin/cygcrypto-1.0.0.dll"
else:
dll_path = "/usr/local/ssl/lib/libcrypto.so"
ssl = ctypes.CDLL(dll_path, ctypes.RTLD_GLOBAL)
assert ssl
except:
dll_path = ctypes.util.find_library('ssl') or ctypes.util.find_library('crypto') or ctypes.util.find_library('libcrypto')
ssl = ctypes.CDLL(dll_path or 'libeay32', ctypes.RTLD_GLOBAL)
return ssl
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
def skip_if_lib_missing(libname, text=None):
"""
pytest decorator to evaluate the required shared lib.
:param libname: Name of the required library.
:param text: Text to put into the reason message
(defaults to 'lib%s.so' % libname)
:return: pytest decorator with a reason.
"""
soname = ctypes.util.find_library(libname)
if not text:
text = "lib%s.so" % libname
# Return pytest decorator.
return skipif(not (soname and ctypes.CDLL(soname)),
reason="required %s missing" % text)
def forget(modname):
"""'Forget' a module was ever imported.
This removes the module from sys.modules and deletes any PEP 3147 or
legacy .pyc and .pyo files.
"""
unload(modname)
for dirname in sys.path:
source = os.path.join(dirname, modname + '.py')
# It doesn't matter if they exist or not, unlink all possible
# combinations of PEP 3147 and legacy pyc and pyo files.
unlink(source + 'c')
unlink(source + 'o')
unlink(importlib.util.cache_from_source(source, debug_override=True))
unlink(importlib.util.cache_from_source(source, debug_override=False))
# Check whether a gui is actually available
def _load_libc():
libc_path = None
try:
libc_path = ctypes.util.find_library('c')
except (OSError, IOError):
# Note: find_library will on some platforms raise these undocumented
# errors, e.g.on android IOError "No usable temporary directory found"
# will be raised.
pass
if libc_path is not None:
return ctypes.CDLL(libc_path)
# Fallbacks
try:
return ctypes.CDLL('libc.so')
except (OSError, IOError):
return ctypes.CDLL('libc.so.6')
def find_library(self, path):
# search first for local libs
if _local_lib_paths:
if not self._local_libs_cache:
self._local_libs_cache = self._find_libs(_local_lib_paths)
if path in self._local_libs_cache:
return self._local_libs_cache[path]
# ctypes tries ldconfig, gcc and objdump. If none of these are
# present, we implement the ld-linux.so search path as described in
# the man page.
result = ctypes.util.find_library(path)
if result:
return result
if self._ld_so_cache is None:
self._create_ld_so_cache()
return self._ld_so_cache.get(path)
def nprocessors():
try:
try:
# Mac OS
libc=ctypes.cdll.LoadLibrary(ctypes.util.find_library('libc'))
v=ctypes.c_int(0)
size=ctypes.c_size_t(ctypes.sizeof(v))
libc.sysctlbyname('hw.ncpu', ctypes.c_voidp(ctypes.addressof(v)), ctypes.addressof(size), None, 0)
return v.value
except:
# Cygwin (Windows) and Linuxes
# Could try sysconf(_SC_NPROCESSORS_ONLN) (LSB) next. Instead, count processors in cpuinfo.
s = open('/proc/cpuinfo', 'r').read()
return s.replace(' ', '').replace('\t', '').count('processor:')
except:
return 1
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
def find_library(self, path):
# search first for local libs
if _local_lib_paths:
if not self._local_libs_cache:
self._local_libs_cache = self._find_libs(_local_lib_paths)
if path in self._local_libs_cache:
return self._local_libs_cache[path]
# ctypes tries ldconfig, gcc and objdump. If none of these are
# present, we implement the ld-linux.so search path as described in
# the man page.
result = ctypes.util.find_library(path)
if result:
return result
if self._ld_so_cache is None:
self._create_ld_so_cache()
return self._ld_so_cache.get(path)
def forget(modname):
"""'Forget' a module was ever imported.
This removes the module from sys.modules and deletes any PEP 3147 or
legacy .pyc and .pyo files.
"""
unload(modname)
for dirname in sys.path:
source = os.path.join(dirname, modname + '.py')
# It doesn't matter if they exist or not, unlink all possible
# combinations of PEP 3147 and legacy pyc and pyo files.
unlink(source + 'c')
unlink(source + 'o')
unlink(importlib.util.cache_from_source(source, debug_override=True))
unlink(importlib.util.cache_from_source(source, debug_override=False))
# Check whether a gui is actually available
def __init__(self, url):
self.libmms = ctypes.cdll.LoadLibrary(ctypes.util.find_library('mms'))
if self.libmms._name is None: # pylint:disable=protected-access
raise download_npo.Error(
'Deze video is in het (oude) MMS/WMV formaat; om dit te'
'downloaden heb je libmms nodig, welke niet is gevonden op je'
'systeem. Zie: http://sourceforge.net/projects/libmms/')
self._libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
mmsh_connect = self.libmms.mmsh_connect
mmsh_connect.restype = ctypes.POINTER(mmsh_t)
if sys.version_info[0] > 2:
url = bytes(url, 'utf-8')
self._mms = mmsh_connect(None, None, url, 128 * 1024)
malloc = self._libc.malloc
malloc.restype = ctypes.POINTER(ctypes.c_char)
self.buf = malloc(8192)
def find_library(self, path):
# search first for local libs
if _local_lib_paths:
if not self._local_libs_cache:
self._local_libs_cache = self._find_libs(_local_lib_paths)
if path in self._local_libs_cache:
return self._local_libs_cache[path]
# ctypes tries ldconfig, gcc and objdump. If none of these are
# present, we implement the ld-linux.so search path as described in
# the man page.
result = ctypes.util.find_library(path)
if result:
return result
if self._ld_so_cache is None:
self._create_ld_so_cache()
return self._ld_so_cache.get(path)
def _dnn_lib():
if _dnn_lib.handle is None:
import ctypes.util
lib_name = ctypes.util.find_library('cudnn')
if lib_name is None and sys.platform == 'win32':
# Update these names when new versions of cudnn are supported.
for name in ['cudnn64_5.dll', 'cudnn64_4.dll']:
lib_name = ctypes.util.find_library(name)
if lib_name:
break
if lib_name is None:
raise RuntimeError('Could not find cudnn library (looked for v4 and v5[.1])')
_dnn_lib.handle = ctypes.cdll.LoadLibrary(lib_name)
cudnn = _dnn_lib.handle
cudnn.cudnnCreate.argtypes = [ctypes.POINTER(ctypes.c_void_p)]
cudnn.cudnnCreate.restype = ctypes.c_int
cudnn.cudnnDestroy.argtypes = [ctypes.c_void_p]
cudnn.cudnnDestroy.restype = ctypes.c_int
return _dnn_lib.handle
def forget(modname):
"""'Forget' a module was ever imported.
This removes the module from sys.modules and deletes any PEP 3147 or
legacy .pyc and .pyo files.
"""
unload(modname)
for dirname in sys.path:
source = os.path.join(dirname, modname + '.py')
# It doesn't matter if they exist or not, unlink all possible
# combinations of PEP 3147 and legacy pyc and pyo files.
unlink(source + 'c')
unlink(source + 'o')
unlink(importlib.util.cache_from_source(source, debug_override=True))
unlink(importlib.util.cache_from_source(source, debug_override=False))
# Check whether a gui is actually available
def _load_libc():
libc_path = None
try:
libc_path = ctypes.util.find_library('c')
except (OSError, IOError):
# Note: find_library will on some platforms raise these undocumented
# errors, e.g.on android IOError "No usable temporary directory found"
# will be raised.
pass
if libc_path is not None:
return ctypes.CDLL(libc_path)
# Fallbacks
try:
return ctypes.CDLL('libc.so')
except (OSError, IOError):
return ctypes.CDLL('libc.so.6')
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
def skip_if_lib_missing(libname, text=None):
"""
pytest decorator to evaluate the required shared lib.
:param libname: Name of the required library.
:param text: Text to put into the reason message
(defaults to 'lib%s.so' % libname)
:return: pytest decorator with a reason.
"""
soname = ctypes.util.find_library(libname)
if not text:
text = "lib%s.so" % libname
# Return pytest decorator.
return skipif(not (soname and ctypes.CDLL(soname)),
reason="required %s missing" % text)
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
def openssl_set_session_cache_mode(context, mode):
assert isinstance(context, OpenSSL.SSL.Context)
try:
import ctypes
SSL_CTRL_SET_SESS_CACHE_MODE = 44
SESS_CACHE_OFF = 0x0
SESS_CACHE_CLIENT = 0x1
SESS_CACHE_SERVER = 0x2
SESS_CACHE_BOTH = 0x3
c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
if hasattr(context, 'set_session_cache_mode'):
context.set_session_cache_mode(c_mode)
elif OpenSSL.__version__ == '0.13':
# http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
if os.name == 'nt':
# https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
else:
import ctypes.util
# FIXME
# ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
except Exception as e:
logging.warning('openssl_set_session_cache_mode failed: %r', e)
libc.py 文件源码
项目:Daniel-Arbuckles-Mastering-Python
作者: PacktPublishing
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def load_library(*alternates):
for base_name in alternates:
lib_name = ctypes.util.find_library(base_name)
try:
if lib_name:
return ctypes.CDLL(lib_name)
else:
return ctypes.CDLL(base_name)
except OSError:
pass
raise OSError('Unable to load any of: {}'.format(alternates))
def locate_library (candidates, find_library=ctypes.util.find_library):
"""Tries to locate a library listed in candidates using the given
find_library() function (or ctypes.util.find_library).
Returns the first library found, which can be the library's name
or the path to the library file, depending on find_library().
Returns None if no library is found.
arguments:
* candidates -- iterable with library names
* find_library -- function that takes one positional arg (candidate)
and returns a non-empty str if a library has been found.
Any "false" value (None,False,empty str) is interpreted
as "library not found".
Defaults to ctypes.util.find_library if not given or
None.
"""
if find_library is None:
find_library = ctypes.util.find_library
use_dll_workaround = (
sys.platform == 'win32' and find_library is ctypes.util.find_library
)
for candidate in candidates:
# Workaround for CPython 3.3 issue#16283 / pyusb #14
if use_dll_workaround:
candidate += '.dll'
libname = find_library(candidate)
if libname:
return libname
# -- end for
return None
def user(pid):
"""
Provides the user a process is running under.
:param int pid: process id of the process to be queried
:returns: **str** with the username a process is running under, **None** if
it can't be determined
"""
if not isinstance(pid, int) or pid < 0:
return None
if stem.util.proc.is_available():
try:
import pwd # only available on unix platforms
uid = stem.util.proc.uid(pid)
if uid and uid.isdigit():
return pwd.getpwuid(int(uid)).pw_name
except:
pass
if is_available('ps'):
results = call('ps -o user %s' % pid, [])
if len(results) >= 2:
return results[1].strip()
return None
def start_time(pid):
"""
Provides the unix timestamp when the given process started.
:param int pid: process id of the process to be queried
:returns: **float** for the unix timestamp when the process began, **None**
if it can't be determined
"""
if not isinstance(pid, int) or pid < 0:
return None
if stem.util.proc.is_available():
try:
return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])
except IOError:
pass
try:
ps_results = call('ps -p %s -o etime' % pid, [])
if len(ps_results) >= 2:
etime = ps_results[1].strip()
return time.time() - stem.util.str_tools.parse_short_time_label(etime)
except:
pass
return None
def set_process_name(process_name):
"""
Renames our current process from "python <args>" to a custom name. This is
best-effort, not necessarily working on all platforms.
**Note:** This might have issues on FreeBSD (:trac:`9804`).
:param str process_name: new name for our process
"""
# This is mostly based on...
#
# http://www.rhinocerus.net/forum/lang-python/569677-setting-program-name-like-0-perl.html#post2272369
#
# ... and an adaptation by Jake...
#
# https://github.com/ioerror/chameleon
#
# A cleaner implementation is available at...
#
# https://github.com/cream/libs/blob/b38970e2a6f6d2620724c828808235be0445b799/cream/util/procname.py
#
# but I'm not quite clear on their implementation, and it only does targeted
# argument replacement (ie, replace argv[0], argv[1], etc but with a string
# the same size).
_set_argv(process_name)
if platform.system() == 'Linux':
_set_prctl_name(process_name)
elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):
_set_proc_title(process_name)
def _set_prctl_name(process_name):
"""
Sets the prctl name, which is used by top and killall. This appears to be
Linux specific and has the max of 15 characters.
This is from...
http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/923034#923034
"""
libc = ctypes.CDLL(ctypes.util.find_library('c'))
name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
name_buffer.value = stem.util.str_tools._to_bytes(process_name)
libc.prctl(PR_SET_NAME, ctypes.byref(name_buffer), 0, 0, 0)
def build_display():
global display, window, x11
if display and window and x11: return
x11 = ctypes.cdll.LoadLibrary(ctypes.util.find_library('X11'))
# Required because we will have multiple threads calling x11,
# such as the listener thread and then main using "move_to".
x11.XInitThreads()
display = x11.XOpenDisplay(None)
# Known to cause segfault in Fedora 23 64bits, no known workarounds.
# http://stackoverflow.com/questions/35137007/get-mouse-position-on-linux-pure-python
window = x11.XDefaultRootWindow(display)
def openLibrary():
global ssl
try:
if sys.platform.startswith("win"):
dll_path = "src/lib/opensslVerify/libeay32.dll"
elif sys.platform == "cygwin":
dll_path = "/bin/cygcrypto-1.0.0.dll"
else:
dll_path = "/usr/local/ssl/lib/libcrypto.so"
ssl = _OpenSSL(dll_path)
assert ssl
except Exception, err:
ssl = _OpenSSL(ctypes.util.find_library('ssl') or ctypes.util.find_library('crypto') or ctypes.util.find_library('libcrypto') or 'libeay32')
def disableSSLCompression():
import ctypes
import ctypes.util
try:
openssl = openLibrary()
openssl.SSL_COMP_get_compression_methods.restype = ctypes.c_void_p
except Exception, err:
logging.debug("Disable SSL compression failed: %s (normal on Windows)" % err)
return False
openssl.sk_zero.argtypes = [ctypes.c_void_p]
openssl.sk_zero(openssl.SSL_COMP_get_compression_methods())
logging.debug("Disabled SSL compression on %s" % openssl)
def __init__(self, board, session):
super(VfsManager, self).__init__("VFS", board)
self.session = session
self.board = board
"""
#print session
from iotronic_lightningrod.modules import vfs_library
fuse=vfs_library.FuseLib("/opt/AAA")
print fuse.getattr("/aaa.txt")
"""
libcPath = ctypes.util.find_library("c")
self.libc = ctypes.CDLL(libcPath)