def find_yajl_ctypes(required):
'''
Finds and loads yajl shared object of the required major
version (1, 2, ...) using ctypes.
'''
# Importing ``ctypes`` should be in scope of this function to prevent failure
# of `backends`` package load in a runtime where ``ctypes`` is not available.
# Example of such environment is Google App Engine (GAE).
from ctypes import util, cdll
so_name = util.find_library('yajl')
if so_name is None:
raise YAJLImportError('YAJL shared object not found.')
yajl = cdll.LoadLibrary(so_name)
require_version(yajl.yajl_version(), required)
return yajl
python类find_library()的实例源码
def ntp_adjtime():
retval = None
try:
libc = cdll.LoadLibrary(find_library("c"))
timex = TimexStruct()
p_timex = pointer(timex)
libc.ntp_adjtime(p_timex)
retval = p_timex.contents
except Exception as e:
return None
return retval
# ---------------------------
def test_load_library(self):
self.assertIsNotNone(libc_name)
if is_resource_enabled("printing"):
print find_library("kernel32")
print find_library("user32")
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def find_yajl_ctypes(required):
'''
Finds and loads yajl shared object of the required major
version (1, 2, ...) using ctypes.
'''
# Importing ``ctypes`` should be in scope of this function to prevent failure
# of `backends`` package load in a runtime where ``ctypes`` is not available.
# Example of such environment is Google App Engine (GAE).
from ctypes import util, cdll
so_name = util.find_library('yajl')
if so_name is None:
raise YAJLImportError('YAJL shared object not found.')
yajl = cdll.LoadLibrary(so_name)
require_version(yajl.yajl_version(), required)
return yajl
def _libnccl():
global nccl_2_0
global lib
global status_codes
global nccl_types
if lib is None:
lib = ctypes.pydll.LoadLibrary(find_library('nccl'))
if hasattr(lib, 'ncclCommDestroy'):
lib.ncclCommDestroy.restype = None
else:
lib = None
if hasattr(lib, 'ncclGroupStart'):
nccl_2_0 = True
status_codes = status_codes_2_0
nccl_types = nccl_types_2_0
return lib
def _e_path_possibilities():
"""Generator yielding possible locations of the enchant library."""
# Allow it to be overridden using an environment variable.
yield os.environ.get("PYENCHANT_LIBRARY_PATH")
# For linuxish systems, allow default soname lookup a chance to succeed.
if sys.platform not in ("win32", "darwin"):
yield "libenchant.so.1.6.0"
yield "libenchant.so.1"
yield "libenchant.so"
# See if ctypes can find the library for us, under various names.
yield find_library("enchant")
yield find_library("libenchant")
yield find_library("libenchant-1")
# Special-case handling for enchant installed by macports.
if sys.platform == 'darwin':
yield "/opt/local/lib/libenchant.dylib"
# On win32 we ship a bundled version of the enchant DLLs.
# Use them if they're present.
def find_cuda():
cuda_home = os.getenv('CUDA_HOME', '/usr/local/cuda')
if not os.path.exists(cuda_home):
# We use nvcc path on Linux and cudart path on macOS
osname = platform.system()
if osname == 'Linux':
cuda_path = find_nvcc()
else:
cudart_path = find_library('cudart')
if cudart_path is not None:
cuda_path = os.path.dirname(cudart_path)
else:
cuda_path = None
if cuda_path is not None:
cuda_home = os.path.dirname(cuda_path)
else:
cuda_home = None
return cuda_home is not None
# Build-specific dependencies.
def _libnccl():
global nccl_2_0
global lib
global status_codes
global nccl_types
if lib is None:
lib = ctypes.pydll.LoadLibrary(find_library('nccl'))
if hasattr(lib, 'ncclCommDestroy'):
lib.ncclCommDestroy.restype = None
else:
lib = None
if hasattr(lib, 'ncclGroupStart'):
nccl_2_0 = True
status_codes = status_codes_2_0
nccl_types = nccl_types_2_0
return lib
def test_load_library(self):
self.assertFalse(libc_name is None)
if is_resource_enabled("printing"):
print(find_library("kernel32"))
print(find_library("user32"))
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def load_dll(libname, fallbacks=None):
lib = find_library(libname)
if lib is not None:
return CDLL(lib)
else:
if fallbacks is not None:
for name in fallbacks:
try:
return CDLL(name)
except OSError:
# move on to the next fallback
pass
# the end
raise OSError(
"Could not find library %s or load any of its variants %s" % (
libname, fallbacks or []))
def test_load_library(self):
self.assertIsNotNone(libc_name)
if is_resource_enabled("printing"):
print find_library("kernel32")
print find_library("user32")
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def test_load_library(self):
self.assertIsNotNone(libc_name)
if is_resource_enabled("printing"):
print find_library("kernel32")
print find_library("user32")
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def __init__(self):
v_posix.PosixMixin.__init__(self)
v_posix.PtraceMixin.__init__(self)
self.libc = ctypes.CDLL(c_util.find_library('c'))
self.myport = self.libc.mach_task_self()
self.libc.mach_port_allocate.argtypes = [ipc_space_t, mach_port_right_t, ctypes.POINTER(mach_port_name_t)]
self.libc.mach_port_allocate.restype = kern_return_t
self.libc.mach_vm_read.argtypes = [ mach_port_t, size_t, size_t, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint32)]
self.libc.mach_vm_read.restype = kern_return_t
self.libc.ptrace.restype = ctypes.c_int
self.libc.ptrace.argtypes = [ctypes.c_int, ctypes.c_uint32, ctypes.c_size_t, ctypes.c_int]
machhelp_path = os.path.join(darwindir, 'machhelper.dylib')
self.machhelper = ctypes.CDLL(machhelp_path)
self.machhelper.platformPs.restype = ctypes.POINTER(ProcessListEntry)
self.useptrace = False
self.portset = self.newMachPort(MACH_PORT_RIGHT_PORT_SET)
self.excport = self.newMachRWPort()
self.addPortToSet(self.excport)
def ptrace(code, pid, addr, data):
"""
The contents of this call are basically cleanly
passed to the libc implementation of ptrace.
"""
global libc
if not libc:
if os.getenv('ANDROID_ROOT'):
cloc = '/system/lib/libc.so'
else:
cloc = cutil.find_library("c")
if not cloc:
raise Exception("ERROR: can't find C library on posix system!")
libc = CDLL(cloc)
libc.ptrace.restype = c_size_t
libc.ptrace.argtypes = [c_int, c_uint32, c_size_t, c_size_t]
return libc.ptrace(code, pid, c_size_t(addr), c_size_t(data))
def test_load_library(self):
self.assertIsNotNone(libc_name)
if is_resource_enabled("printing"):
print find_library("kernel32")
print find_library("user32")
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def test_load_library(self):
self.assertIsNotNone(libc_name)
if test.support.verbose:
print(find_library("kernel32"))
print(find_library("user32"))
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def test_load_library(self):
self.assertFalse(libc_name is None)
if is_resource_enabled("printing"):
print find_library("kernel32")
print find_library("user32")
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def _load_or_error(name):
path = util.find_library(name)
if path is not None:
return CDLL(path)
# On iOS (and probably also watchOS and tvOS), ctypes.util.find_library doesn't work and always returns None.
# This is because the sandbox hides all system libraries from the filesystem and pretends they don't exist.
# However they can still be loaded if the path is known, so we try to load the library from a few known locations.
for loc in _lib_path:
try:
return CDLL(os.path.join(loc, "lib" + name + ".dylib"))
except OSError:
pass
for loc in _framework_path:
try:
return CDLL(os.path.join(loc, name + ".framework", name))
except OSError:
pass
raise ValueError("Library {!r} not found".format(name))
def psloadlib(name):
""" Loads driver library
:param name: driver name
:type name: str
:returns: ctypes reference to the library
:rtype: object
"""
result = None
try:
if sys.platform == 'win32':
result = ctypes.WinDLL(find_library(name))
else:
result = cdll.LoadLibrary(find_library(name))
except OSError as ex:
print name, "import(%d): Library not found" % sys.exc_info()[-1].tb_lineno
return result
def test_load_library(self):
self.assertIsNotNone(libc_name)
if test.support.verbose:
print(find_library("kernel32"))
print(find_library("user32"))
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
def initialize(path=None):
"""Load `libeXosip2` into this Python library
:param str path: `libeXosip2` SO/DLL path, `default` is `None`.
When `None` or empty string, the function will try to find and load so/dll by :data:`DLL_NAME`
"""
_logger.info('initialize: >>> path=%s', path)
if globs.libexosip2:
raise RuntimeError('library eXosip2 already loaded')
if not path:
_logger.debug('initialize: find_library "%s"', DLL_NAME)
path = find_library(DLL_NAME)
if not path:
raise RuntimeError('Failed to find library {}'.format(DLL_NAME))
_logger.debug('initialize: CDLL %s', path)
globs.libexosip2 = CDLL(path)
if not globs.libexosip2:
raise RuntimeError('Failed to load library {}'.format(path))
_logger.debug('initialize: libexosip2=%s', globs.libexosip2)
for cls in globs.func_classes:
cls.bind()
_logger.info('initialize: <<<')
def zerome(string):
# find the header size with a dummy string
dummy = "header finder"
header = ctypes.string_at(id(dummy), sys.getsizeof(dummy)).find(dummy)
location = id(string) + header
size = sys.getsizeof(string) - header
if platform.system() == 'Windows':
memset = ctypes.cdll.msvcrt.memset
else:
libc = find_library('c')
memset = ctypes.CDLL(libc).memset
# For OS X, the above should work, but if it doesn't:
# memset = ctypes.CDLL('libc.dylib').memset
print "Clearing 0x%08x size %i bytes" % (location, size)
memset(location, 0, size)
#string still with us?
print ctypes.string_at(location, size)
def __init__(self):
''' MacOS X initialisations. '''
coregraphics = find_library('CoreGraphics')
if not coregraphics:
raise ScreenshotError('No CoreGraphics library found.')
self.core = cdll.LoadLibrary(coregraphics)
self._set_argtypes()
self._set_restypes()
def _init():
"""
Loads the shared library through ctypes and returns a library
L{ctypes.CDLL} instance
"""
return ctypes.cdll.LoadLibrary(find_library('magic'))
def _importLibrary(self):
piLibName= 'pi_pi_gcs2'
pilib= find_library(piLibName)
if pilib is None:
raise PIException("Library %s not found" % piLibName)
self._lib= ctypes.CDLL(pilib)
def setUp(self):
self.libc= ctypes.CDLL(find_library("c"))
self.libm= ctypes.CDLL(find_library("m"))
def load_libsodium():
global loaded, libsodium, buf
from ctypes.util import find_library
for p in ('sodium',):
libsodium_path = find_library(p)
if libsodium_path:
break
else:
raise Exception('libsodium not found')
logging.info('loading libsodium from %s', libsodium_path)
libsodium = CDLL(libsodium_path)
libsodium.sodium_init.restype = c_int
libsodium.crypto_stream_salsa20_xor_ic.restype = c_int
libsodium.crypto_stream_salsa20_xor_ic.argtypes = (c_void_p, c_char_p,
c_ulonglong,
c_char_p, c_ulonglong,
c_char_p)
libsodium.crypto_stream_chacha20_xor_ic.restype = c_int
libsodium.crypto_stream_chacha20_xor_ic.argtypes = (c_void_p, c_char_p,
c_ulonglong,
c_char_p, c_ulonglong,
c_char_p)
libsodium.sodium_init()
buf = create_string_buffer(buf_size)
loaded = True
def load_openssl():
global loaded, libcrypto, buf
from ctypes.util import find_library
for p in ('crypto', 'eay32', 'libeay32'):
libcrypto_path = find_library(p)
if libcrypto_path:
break
else:
raise Exception('libcrypto(OpenSSL) not found')
logging.info('loading libcrypto from %s', libcrypto_path)
libcrypto = CDLL(libcrypto_path)
libcrypto.EVP_get_cipherbyname.restype = c_void_p
libcrypto.EVP_CIPHER_CTX_new.restype = c_void_p
libcrypto.EVP_CipherInit_ex.argtypes = (c_void_p, c_void_p, c_char_p,
c_char_p, c_char_p, c_int)
libcrypto.EVP_CipherUpdate.argtypes = (c_void_p, c_void_p, c_void_p,
c_char_p, c_int)
libcrypto.EVP_CIPHER_CTX_cleanup.argtypes = (c_void_p,)
libcrypto.EVP_CIPHER_CTX_free.argtypes = (c_void_p,)
if hasattr(libcrypto, 'OpenSSL_add_all_ciphers'):
libcrypto.OpenSSL_add_all_ciphers()
buf = create_string_buffer(buf_size)
loaded = True
def test_find(self):
for name in ("c", "m"):
lib = find_library(name)
if lib:
cdll.LoadLibrary(lib)
CDLL(lib)
def test_open(self):
libc_name = find_library("c")
if libc_name is None:
raise unittest.SkipTest("Unable to find C library")
libc = CDLL(libc_name, use_errno=True)
if os.name == "nt":
libc_open = libc._open
else:
libc_open = libc.open
libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1)
self.assertEqual(get_errno(), errno.ENOENT)
self.assertEqual(set_errno(32), errno.ENOENT)
self.assertEqual(get_errno(), 32)
if threading:
def _worker():
set_errno(0)
libc = CDLL(libc_name, use_errno=False)
if os.name == "nt":
libc_open = libc._open
else:
libc_open = libc.open
libc_open.argtypes = c_char_p, c_int
self.assertEqual(libc_open("", 0), -1)
self.assertEqual(get_errno(), 0)
t = threading.Thread(target=_worker)
t.start()
t.join()
self.assertEqual(get_errno(), 32)
set_errno(0)