def check_extension(ext): lib = find_library(ext.libname) if ext.required and not lib: raise SystemExit(err_msg.format(ext.name, ext.min_ver, ext.url)) elif lib: curr_ver = c_char_p.in_dll(cdll.LoadLibrary(lib), ext.ver_char_p).value if curr_ver.decode() < ext.min_ver: raise SystemExit(err_msg.format(ext.name, ext.min_ver, ext.url)) return lib
def status(self): """ Prints a summary of the current status of the simulation. """ s= "" s += "---------------------------------\n" s += "REBOUND version: \t%s\n" %c_char_p.in_dll(clibrebound, "reb_version_str").value.decode('ascii') s += "REBOUND built on: \t%s\n" %c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii') s += "Number of particles: \t%d\n" %self.N s += "Selected integrator: \t" + self.integrator + "\n" s += "Simulation time: \t%f\n" %self.t s += "Current timestep: \t%f\n" %self.dt if self.N>0: s += "---------------------------------\n" for p in self.particles: s += str(p) + "\n" s += "---------------------------------" print(s)
def __init__(self, options='-nosplash', matlab_root=None, buffer_size=0): system = platform.system() if (matlab_root is None) and ('MATLABROOT' in os.environ): matlab_root = os.environ['MATLABROOT'] if matlab_root is None: matlab_root = find_matlab_root() if matlab_root is None: raise RuntimeError("MATLAB location is unknown (try to initialize MatlabSession with matlab_root set properly).") self._matlab_root = matlab_root engine, libeng, libmx = load_engine_and_libs(matlab_root, options) self._libeng = libeng self._libmx = libmx self._ep = engine ### MATLAB/libeng version self.version = c_char_p.in_dll(libeng, "libeng_version").value ### Setup the output buffer if buffer_size != 0: self._output_buffer = ctypes.create_string_buffer(buffer_size) self._libeng.engOutputBuffer( self._ep, self._output_buffer, buffer_size-1 ) else: self._output_buffer = None ### Workspace object self.workspace = Workspace(weakref.ref(self)) # last step: setupt magics, if we are in IPython try: ip = get_ipython() except NameError: return else: if 'matlab' not in ip.magics_manager.magics: # in IPython but we are the first Client. # activate a default view for parallel magics. self.activate()
def set_char_p(lib: CDLL, name: str, value: Union[bytes, str]): try: if is_str(value): value = c_stob(value) elif not is_bytes(value): raise TypeError(f"Exception bytes or str, found {type(value)}") c_char_p.in_dll(lib, name).value = value except Exception as e: log.w(f"set_char_p failed: {e}") raise CException(e)
def status(self): """ Prints a summary of the current status of the simulation. """ s = "" s += "---------------------------------\n" s += "REBOUND version: \t%s\n" % c_char_p.in_dll( clibrebound, "reb_version_str").value.decode('ascii') s += "REBOUND built on: \t%s\n" % c_char_p.in_dll( clibrebound, "reb_build_str").value.decode('ascii') s += "Number of particles: \t%d\n" % self.N s += "Selected integrator: \t" + self.integrator + "\n" s += "Simulation time: \t%f\n" % self.t s += "Current timestep: \t%f\n" % self.dt if self.N > 0: s += "---------------------------------\n" for p in self.particles: s += str(p) + "\n" s += "---------------------------------" print(s)
def ta(specString): if _taDisabled: return "" # NOTE: not checking for errors if specString == "f": return "\033[0m" # frequent use t = type(specString) if t is bytes: pass elif t is str: specString = specString.encode() else: raise TypeError("argument to ‘ta’ should be of type str or bytes") codeSeq = _ta_n(specString, len(specString)) if codeSeq == b"": raise TextAttrError(c_char_p.in_dll(_lib, "taErrorMsg").value.decode()) return codeSeq.decode()
# Find suffix import sysconfig suffix = sysconfig.get_config_var('EXT_SUFFIX') if suffix is None: suffix = ".so" # Import shared library import os import warnings pymodulepath = os.path.dirname(__file__) from ctypes import cdll, c_char_p clibcelmech = cdll.LoadLibrary(pymodulepath + "/../libcelmech" + suffix) # Version __version__ = c_char_p.in_dll(clibcelmech, "celmech_version_str").value.decode('ascii') # Build __build__ = c_char_p.in_dll(clibcelmech, "celmech_build_str").value.decode('ascii') # Githash __githash__ = c_char_p.in_dll(clibcelmech, "celmech_githash_str").value.decode('ascii') # Check for version try: moduleversion = pkg_resources.require("celmech")[0].version libcelmechversion = __version__ if moduleversion != libcelmechversion: warnings.warn(
# include from async.h type.h from ctypes import CFUNCTYPE, POINTER, Structure, c_char_p, pointer, c_long, c_voidp, c_ulong, c_int, cast, byref, c_size_t, c_void_p import ctypes from .base import lib, s_strdup, LwqqBase from .vplist import Command __all__ = [ 'Event', 'Events', 'Arguments', 'has_feature', 'version', 'VerifyCode' ] feature = c_long.in_dll(lib, "lwqq_features").value version = c_char_p.in_dll(lib, 'lwqq_version').value def has_feature(f): return feature & f class Event(LwqqBase): class T(Structure): _fields_ = [('result', c_int), ('failcode', c_int), ('lc', c_voidp)] PT = POINTER(T) eventsref = [] @property def result(self): return self.ref[0].result
# Find suffix import sysconfig suffix = sysconfig.get_config_var('EXT_SUFFIX') if suffix is None: suffix = ".so" # Import shared library import os pymodulepath = os.path.dirname(__file__) from ctypes import cdll, c_char_p clibrebound = cdll.LoadLibrary(pymodulepath + "/../librebound" + suffix) # Check for version try: moduleversion = pkg_resources.require("rebound")[0].version libreboundversion = c_char_p.in_dll( clibrebound, "reb_version_str").value.decode("ascii") if moduleversion != libreboundversion: print( "WARNING: python module and librebound have different version numbers: '%s' vs '%s'.\n" % (moduleversion, libreboundversion)) except: # Might fails on python3 versions, but not important pass # Built str def build_str(): return c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii') # Exceptions
#!/usr/bin/env python # This is free and unencumbered software released into the public domain. from ctypes import CDLL, c_bool, c_char_p, c_short, c_size_t from ctypes.util import find_library try: libcpr = CDLL('libcpr.so.0') except OSError: libcpr_path = find_library('cpr') if libcpr_path: libcpr = CDLL(libcpr_path) else: raise OSError('libcpr shared library not found') VERSION_STRING = c_char_p.in_dll(libcpr, 'cpr_version_string').value VERSION_MAJOR = c_short.in_dll(libcpr, 'cpr_version_major').value VERSION_MINOR = c_short.in_dll(libcpr, 'cpr_version_minor').value VERSION_PATCH = c_short.in_dll(libcpr, 'cpr_version_patch').value def version_string(): return VERSION_STRING has_feature = libcpr.cpr_feature_exists has_feature.argtypes = [c_char_p] has_feature.restype = c_bool has_module = libcpr.cpr_module_exists has_module.argtypes = [c_char_p]
def load_engine_and_libs(matlab_root, options): """Load and return `libeng` and `libmx`. Start and return MATLAB engine. Returns ------- engine libeng libmx """ if sys.maxsize > 2**32: bits = '64bit' else: bits = '32bit' system = platform.system() if system == 'Linux': if bits == '64bit': lib_dir = join(matlab_root, "bin", "glnxa64") else: lib_dir = join(matlab_root, "bin", "glnx86") check_python_matlab_architecture(bits, lib_dir) libeng = Library( join(lib_dir, 'libeng.so') ) libmx = Library( join(lib_dir, 'libmx.so') ) command = "{executable} {options}".format( executable=join(matlab_root, 'bin', 'matlab'), options=options ) ### Check for /bin/csh if not os.path.exists("/bin/csh"): warnings.warn("MATLAB engine requires /bin/csh. Please install it on your system or matlab_wrapper will not work properly.") elif system == 'Windows': if bits == '64bit': lib_dir = join(matlab_root, "bin", "win64") else: lib_dir = join(matlab_root, "bin", "win32") check_python_matlab_architecture(bits, lib_dir) ## We need to modify PATH, to find MATLAB libs if lib_dir not in os.environ['PATH']: os.environ['PATH'] = lib_dir + ';' + os.environ['PATH'] libeng = Library('libeng') libmx = Library('libmx') command = None elif system == 'Darwin': if bits == '64bit': lib_dir = join(matlab_root, "bin", "maci64") else: unsupported_platform(system, bits) check_python_matlab_architecture(bits, lib_dir) libeng = Library( join(lib_dir, 'libeng.dylib') ) libmx = Library( join(lib_dir, 'libmx.dylib') ) command = "{executable} {options}".format( executable=join(matlab_root, 'bin', 'matlab'), options=options ) else: unsupported_platform(system, bits) ### Check MATLAB version try: version_str = c_char_p.in_dll(libeng, "libeng_version").value version = tuple([int(v) for v in version_str.split('.')[:2]]) except ValueError: warnings.warn("Unable to identify MATLAB (libeng) version.") version = None if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'): warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'): warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") ### Start the engine engine = libeng.engOpen(command) return engine, libeng, libmx, version
from sensors import stdc version_info = (0, 1, 0) __version__ = '.'.join(map(str, version_info)) __version__ = '0.1.0' __date__ = '2019-03-09' __author__ = "Richard Hull / Marc 'BlackJack' Rintsch" __contact__ = '*****@*****.**' __license__ = 'LGPL v2.1' API_VERSION = 4 DEFAULT_CONFIG_FILENAME = '/etc/sensors3.conf' LIB_FILENAME = os.environ.get('SENSORS_LIB') or find_library('sensors') SENSORS_LIB = CDLL(LIB_FILENAME) VERSION = c_char_p.in_dll(SENSORS_LIB, 'libsensors_version').value MAJOR_VERSION = version_info[0] class SensorsError(Exception): def __init__(self, message, error_number=None): Exception.__init__(self, message) self.error_number = error_number def _error_check(result, _func, _arguments): if result < 0: raise SensorsError(_strerror(result), result) return result
def API(dllname=None): """Return ctypes interface to functions of ICSx64 DLL.""" from ctypes import ( c_int, c_int32, c_int64, c_size_t, c_ssize_t, c_double, c_float, c_char_p, POINTER, ) c_ssize_t_p = POINTER(c_ssize_t) c_double_p = POINTER(c_double) handle_t = c_size_t if dllname is None: dllname = os.path.join(os.path.dirname(__file__), 'ICSx64.dll') api = ctypes.CDLL(dllname) api.VERSION = c_char_p.in_dll(api, 'ICS_VERSION').value.decode('ascii') api.MODE_FCS = 2 api.MODE_CC = 4 api.AXIS0 = 1 api.AXIS1 = 8 api.AXIS2 = 16 api.FALSE = 0 api.TRUE = 1 api.OK = 0 api.ERROR = -1 api.VALUE_ERROR = -2 api.MEMORY_ERROR = -3 api.NOTIMPLEMENTD_ERROR = -4 api.VALUE_ERROR1 = -201 api.VALUE_ERROR2 = -202 api.VALUE_ERROR3 = -203 api.VALUE_ERROR4 = -204 api.VALUE_ERROR5 = -205 api.VALUE_ERROR6 = -206 api.VALUE_ERROR7 = -207 api.VALUE_ERROR8 = -208 api.VALUE_ERROR9 = -209 api.MODE_DEFAULT = 0 api.MODE_TIME = 1 # do not center correlation results in axis 0 (time) api.MODE_FCS = 2 # normalize correlation results according to FCS api.MODE_CC = 4 # allocate second buffer for cross correlation api.AXIS0 = 1 # do not center correlation results in axis 0 api.AXIS1 = 8 # do not center correlation results in axis 1 api.AXIS2 = 16 # do not center correlation results in axis 2 api.MASK_DEFAULT = 0 api.MASK_ANY = 0 # any one value must be True api.MASK_FIRST = 1 # first mask value must be True api.MASK_CENTER = 2 # center mask value must be True api.MASK_ALL = 4 # all mask values must be True api.MASK_CLEAR = 32 # clear output if not calculated api.RADIUS = 1 api.DIAMETER = 2 api.NLSP_ND = 1 api.NLSP_1DPCF = 100 api.ICS_DECONV_DEFAULT = 1 api.ICS_DECONV_RICHARDSON_LUCY = 1 api.ICS_DECONV_WIENER = 2 api.ICS_DECONV_NOPAD = 256 api.DTYPES = {'l': 'i', 'i': 'i', 'h': 'h', 'H': 'H', 'd': 'd', 'f': 'f'} def ndpointer(dtype=None, ndim=None, shape=None, flags=None, null=False): """Return numpy.ctypes.ndpointer type that also accepts None/NULL.""" cls = numpy.ctypeslib.ndpointer(dtype, ndim, shape, flags) if not null: return cls from_param_ = cls.from_param def from_param(cls, param): if param is None: return param return from_param_(param) cls.from_param = classmethod(from_param) return cls def outer(a, b, skip=tuple()): return ((x, y) for x in a for y in b if (x, y) not in skip) # rfft#d_ functions for nd in (1, 2, 3): rfftnd = f'rfft{nd}d_' func = getattr(api, rfftnd + 'new') setattr(func, 'argtypes', [c_ssize_t, c_int]) setattr(func, 'restype', handle_t) func = getattr(api, rfftnd + 'del') setattr(func, 'argtypes', [handle_t]) setattr(func, 'restype', None) func = getattr(api, rfftnd + 'mode') setattr(func, 'argtypes', [c_int]) setattr(func, 'restype', None) for i, o in outer('dfihH', 'df'): ai = ndpointer(dtype=i, ndim=nd) ao = ndpointer(dtype=o, ndim=nd) func = getattr(api, rfftnd + f'autocorrelate_{i}{o}') setattr(func, 'argtypes', [handle_t, ai, ao, c_ssize_t_p]) setattr(func, 'restype', c_int) func = getattr(api, rfftnd + f'crosscorrelate_{i}{o}') setattr( func, 'argtypes', [handle_t, ai, ai, ao, c_ssize_t_p, c_ssize_t_p], ) setattr(func, 'restype', c_int) # nlsp class # TODO: test nlsp_ functions api.nlsp_new.restype = handle_t api.nlsp_new.argtypes = [c_int, c_ssize_t_p] api.nlsp_del.restype = None api.nlsp_del.argtypes = [handle_t] api.nlsp_get.restype = c_int api.nlsp_get.argtypes = [ handle_t, c_ssize_t_p, c_ssize_t_p, c_double_p, c_double_p, ] api.nlsp_set.restype = c_int api.nlsp_set.argtypes = [ handle_t, c_ssize_t, c_ssize_t, ndpointer(dtype='float64', shape=(6, ), null=True), c_double, c_double, ] for dt in 'fd': func = getattr(api, f'nlsp_eval_{dt}') setattr(func, 'restype', c_int) setattr(func, 'argtypes', [handle_t, ndpointer(dtype=dt), c_ssize_t_p]) func = getattr(api, f'nlsp_solve_{dt}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ handle_t, ndpointer(dtype=dt), # data c_ssize_t_p, # strides ndpointer(dtype='float64', ndim=1), # extra ndpointer(dtype='float64', ndim=1, null=True), # guess ndpointer(dtype='float64', ndim=1, null=True), # bounds ndpointer(dtype='float64', ndim=1, null=True), # datasolution ], ) # xyt class api.yxt_new.restype = handle_t api.yxt_new.argtypes = [c_ssize_t_p] api.yxt_del.restype = None api.yxt_del.argtypes = [handle_t] api.yxt_get_buffer.restype = c_double_p api.yxt_get_buffer.argtypes = [handle_t, c_ssize_t_p, c_ssize_t_p] for ti, to in outer('dfihH', 'df'): # yxt_ipcf_* func = getattr(api, f'yxt_ipcf_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ handle_t, ndpointer(dtype=ti, ndim=3, null=True), # data ndpointer(dtype=ti, ndim=3, null=True), # channel c_ssize_t_p, # strides ndpointer(dtype=to, ndim=4), # out c_ssize_t_p, # outstrides ndpointer(dtype='intp', ndim=1), # points c_ssize_t, # npoints ndpointer(dtype='intp', ndim=1), # bins c_ssize_t, # nbins c_double, # threshold c_double, # filter c_int, # nthreads ], ) # yxt_apcf_* func = getattr(api, f'yxt_apcf_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ handle_t, ndpointer(dtype=ti, ndim=2, null=True), # data c_ssize_t_p, # strides ndpointer(dtype=to, ndim=3), # out c_ssize_t_p, # outstrides ndpointer(dtype='intp', ndim=1), # bins c_ssize_t, # nbins c_int, # autocorr c_double, # filter c_int, # nthreads ], ) # yxt_imsd_* func = getattr(api, f'yxt_imsd_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ handle_t, ndpointer(dtype=ti, ndim=3, null=True), # data c_ssize_t_p, # strides ndpointer(dtype=ti, ndim=3, null=True), # data1 c_ssize_t_p, # strides1 ndpointer(dtype='int32', ndim=2, null=True), # mask c_ssize_t_p, # maskstrides c_int, # maskmode ndpointer(dtype=to, ndim=5), # out c_ssize_t_p, # outstrides c_ssize_t_p, # blocks ndpointer(dtype='intp', ndim=1, null=True), # bins c_ssize_t, # nbins c_double, # filter c_int, # nthreads ], ) # yxt_lstics_* func = getattr(api, f'yxt_lstics_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ handle_t, ndpointer(dtype=ti, ndim=3, null=True), # data c_ssize_t_p, # strides ndpointer(dtype=ti, ndim=3, null=True), # data1 c_ssize_t_p, # strides1 ndpointer(dtype='int32', ndim=2, null=True), # mask c_ssize_t_p, # maskstrides c_int, # maskmode ndpointer(dtype=to, ndim=5), # out c_ssize_t_p, # outstrides ndpointer(dtype='intp', ndim=3), # lines c_ssize_t_p, # lineshape c_ssize_t_p, # blocks ndpointer(dtype='intp', ndim=1), # bins c_ssize_t, # nbins c_double, # filter c_int, # nthreads ], ) # ipcf_nlsp_1dpcf for dt in 'f': func = getattr(api, f'ipcf_nlsp_1dpcf_{dt}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ ndpointer(dtype=dt, ndim=4), # ipcf c_ssize_t_p, # shape c_ssize_t_p, # strides ndpointer(dtype=dt, ndim=1), # times ndpointer(dtype=dt, ndim=1), # distances ndpointer(dtype=dt, ndim=1), # args ndpointer(dtype=dt, ndim=1, null=True), # bounds ndpointer(dtype=dt, ndim=4, null=True), # ix c_ssize_t_p, # stridesx ndpointer(dtype=dt, ndim=4, null=True), # ifx c_ssize_t_p, # stridesfx ndpointer(dtype=dt, ndim=4, null=True), # status c_ssize_t_p, # stridestatus ndpointer(dtype=dt, ndim=1, null=True), # settings c_int, # average (bool) c_int, # nthreads ], ) # subtract_immobile, yxt_correct_bleaching for dt in 'ihH': ai = ndpointer(dtype=dt, ndim=3) func = getattr(api, f'yxt_subtract_immobile_{dt}') setattr(func, 'argtypes', [ai, c_ssize_t_p, c_ssize_t_p, c_int]) setattr(func, 'restype', c_int) func = getattr(api, f'yxt_correct_bleaching_{dt}') setattr( func, 'argtypes', [ ai, c_ssize_t_p, c_ssize_t_p, ndpointer(dtype='double', ndim=2), c_ssize_t_p, c_double, c_int, ], ) setattr(func, 'restype', c_int) # yxt_dft for ti, to in outer('dfihH', 'df'): if ti + to in 'dfd': continue func = getattr(api, f'yxt_dft_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ ndpointer(dtype=ti, ndim=3), # data c_ssize_t_p, # shape c_ssize_t_p, # strides ndpointer(dtype=to, ndim=3), # out c_ssize_t_p, # outshape c_ssize_t_p, # outstrides c_int, # nthreads ], ) # zyx_deconv try: for ti, to in ('ff', 'dd', 'Hf'): # outer('fH', 'f'): func = getattr(api, f'zyx_deconv_{ti}{to}') setattr(func, 'restype', c_int) setattr( func, 'argtypes', [ ndpointer(dtype=ti, ndim=3), # image c_ssize_t_p, # shape c_ssize_t_p, # strides ndpointer(dtype=ti, ndim=3), # psf c_ssize_t_p, # shape c_ssize_t_p, # strides ndpointer(dtype=to, ndim=3), # out c_ssize_t_p, # outshape c_ssize_t_p, # outstrides c_int, # niter c_int, # mode c_int, # nthreads ], ) except AttributeError: pass # helper functions api.radial.restype = c_ssize_t api.radial.argtypes = [ ndpointer(dtype='intp', ndim=3), c_ssize_t, c_ssize_t, ndpointer(dtype='float64', ndim=1), c_int, ] api.circle.restype = c_ssize_t api.circle.argtypes = [ c_ssize_t, ndpointer(dtype='intp', ndim=2, null=True), c_ssize_t, ] api.logbins.restype = c_ssize_t api.logbins.argtypes = [ c_ssize_t, c_ssize_t, ndpointer(dtype='intp', ndim=1), ] api.points2distances_f.restype = c_float api.points2distances_f.argtypes = [ ndpointer(dtype='intp', ndim=2), c_ssize_t, c_float, ndpointer(dtype='float32', ndim=1), ] api.points2distances_d.restype = c_double api.points2distances_d.argtypes = [ ndpointer(dtype='intp', ndim=1), c_ssize_t, c_double, ndpointer(dtype='float64', ndim=1), ] api.bins2times_f.restype = c_float api.bins2times_f.argtypes = [ ndpointer(dtype='intp', ndim=1), c_ssize_t, c_float, ndpointer(dtype='float32', ndim=1), ] api.bins2times_d.restype = c_double api.bins2times_d.argtypes = [ ndpointer(dtype='intp', ndim=1), c_ssize_t, c_double, ndpointer(dtype='float64', ndim=1), ] api.nextpow2_i.restype = c_int32 api.nextpow2_i.argtypes = [c_int32] api.nextpow2_q.restype = c_int64 api.nextpow2_q.argtypes = [c_int64] return api
# Find suffix import sysconfig suffix = sysconfig.get_config_var('EXT_SUFFIX') if suffix is None: suffix = ".so" # Import shared library import os import warnings pymodulepath = os.path.dirname(__file__) from ctypes import cdll, c_char_p clibrebound = cdll.LoadLibrary(pymodulepath+"/../librebound"+suffix) # Version __version__ = c_char_p.in_dll(clibrebound, "reb_version_str").value.decode('ascii') # Build __build__ = c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii') # Check for version try: moduleversion = pkg_resources.require("rebound")[0].version libreboundversion = __version__ if moduleversion != libreboundversion: warnings.warn("WARNING: python module and librebound have different version numbers: '%s' vs '%s'.\n" %(moduleversion, libreboundversion), ImportWarning) except: # Might fails on python3 versions, but not important pass # Exceptions
zippath = dirpath.replace(dir, zipdir, 1) for f in filenames: zipfile.write(os.path.join(dirpath, f), os.path.join(zippath, f)) class VersionError(Exception): pass try: dickinson = CDLL( (platform.system() == "Windows" and "dickinson.dll") or (platform.system().startswith("Darwin") and "libdickinson.dylib") or "libdickinson.so" ) dickinson_version = c_char_p.in_dll(dickinson, "dickinson_version").value.decode("ascii") if dickinson_version != "dev" and parse_version(dickinson_version) < parse_version(REQUIRED_DICKINSON_VERSION): raise VersionError("Too old version of dickinson: {0}".format(dickinson_version)) except OSError as e: sys.stderr.write(str(e) + "\n") sys.stderr.write( textwrap.dedent( """ Please make sure you have installed dickinson (see http://dickinson.readthedocs.org/). """ ) ) sys.exit(1) except ValueError as e: sys.stderr.write(str(e) + "\n")
@see: https://github.com/paroj/sensors.py @copyright: LGPLv2 (same as libsensors) <http://opensource.org/licenses/LGPL-2.1> """ import ctypes.util from ctypes import cdll, c_void_p, c_char_p, Structure, c_short, c_int, c_uint, POINTER, byref, create_string_buffer, \ cast, c_double from typing import Tuple, Union, Optional _LIBC = cdll.LoadLibrary(ctypes.util.find_library("c")) # see https://github.com/paroj/sensors.py/issues/1 _LIBC.free.argtypes = [c_void_p] _HDL = cdll.LoadLibrary(ctypes.util.find_library("sensors")) VERSION = c_char_p.in_dll(_HDL, "libsensors_version").value.decode("ascii") class SensorsError(Exception): pass class ErrorWildcards(SensorsError): pass class ErrorNoEntry(SensorsError): pass class ErrorAccessRead(SensorsError, OSError):
def get_char_p(lib: CDLL, name: str) -> str: try: return c_btos(c_char_p.in_dll(lib, name).value) except Exception as e: log.w(f"get_char_p failed: {e}") raise CException(e)
#!/usr/bin/env python # This is free and unencumbered software released into the public domain. from ctypes import CDLL, c_bool, c_char_p, c_short, c_size_t from ctypes.util import find_library try: libcpr = CDLL('libcpr.so.0') except OSError: libcpr_path = find_library('cpr') if libcpr_path: libcpr = CDLL(libcpr_path) else: raise OSError('libcpr shared library not found') VERSION_STRING = c_char_p.in_dll(libcpr, 'cpr_version_string').value VERSION_MAJOR = c_short.in_dll(libcpr, 'cpr_version_major').value VERSION_MINOR = c_short.in_dll(libcpr, 'cpr_version_minor').value VERSION_PATCH = c_short.in_dll(libcpr, 'cpr_version_patch').value def version_string(): return VERSION_STRING has_feature = libcpr.cpr_feature_exists has_feature.argtypes = [c_char_p] has_feature.restype = c_bool has_module = libcpr.cpr_module_exists has_module.argtypes = [c_char_p] has_module.restype = c_bool def sizeof(struct_type):
def build_str(): return c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii')
assert(dirpath.startswith(dir)) zippath = dirpath.replace(dir, zipdir, 1) for f in filenames: zipfile.write(os.path.join(dirpath, f), os.path.join(zippath, f)) class VersionError(Exception): pass try: dickinson = CDLL( (platform.system() == 'Windows' and 'dickinson.dll') or (platform.system().startswith('Darwin') and 'libdickinson.dylib') or 'libdickinson.so') dickinson_version = c_char_p.in_dll(dickinson, 'dickinson_version' ).value.decode('ascii') if dickinson_version != 'dev' and parse_version(dickinson_version) \ < parse_version(REQUIRED_DICKINSON_VERSION): raise VersionError('Too old version of dickinson: {0}'.format( dickinson_version)) except OSError as e: sys.stderr.write(str(e) + '\n') sys.stderr.write(textwrap.dedent(''' Please make sure you have installed dickinson (see http://dickinson.readthedocs.org/). ''')) sys.exit(1) except ValueError as e: sys.stderr.write(str(e) + '\n') sys.stderr.write(textwrap.dedent(''' Apparently the version of dickinson that is installed doesn't export
# Find suffix import sysconfig suffix = sysconfig.get_config_var('EXT_SUFFIX') if suffix is None: suffix = ".so" # Import shared library import os pymodulepath = os.path.dirname(__file__) from ctypes import cdll, c_char_p clibrebound = cdll.LoadLibrary(pymodulepath+"/../librebound"+suffix) # Check for version try: moduleversion = pkg_resources.require("rebound")[0].version libreboundversion = c_char_p.in_dll(clibrebound, "reb_version_str").value.decode("ascii") if moduleversion != libreboundversion: print("WARNING: python module and librebound have different version numbers: '%s' vs '%s'.\n" %(moduleversion, libreboundversion)) except: # Might fails on python3 versions, but not important pass # Built str def build_str(): return c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii') # Exceptions class SimulationError(Exception): """The simulation exited with a generic error.""" pass
def path_statepoint(self): path = c_char_p.in_dll(_dll, 'path_statepoint').value return path.decode()
def load_engine_and_libs(matlab_root, options): """Load and return `libeng` and `libmx`. Start and return MATLAB engine. Returns ------- engine libeng libmx """ if sys.maxsize > 2**32: bits = '64bit' else: bits = '32bit' system = platform.system() if system == 'Linux': if bits == '64bit': lib_dir = join(matlab_root, "bin", "glnxa64") else: lib_dir = join(matlab_root, "bin", "glnx86") check_python_matlab_architecture(bits, lib_dir) libeng = Library(join(lib_dir, 'libeng.so')) libmx = Library(join(lib_dir, 'libmx.so')) command = "{executable} {options}".format(executable=join( matlab_root, 'bin', 'matlab'), options=options) ### Check for /bin/csh if not os.path.exists("/bin/csh"): warnings.warn( "MATLAB engine requires /bin/csh. Please install it on your system or matlab_wrapper will not work properly." ) elif system == 'Windows': if bits == '64bit': lib_dir = join(matlab_root, "bin", "win64") else: lib_dir = join(matlab_root, "bin", "win32") check_python_matlab_architecture(bits, lib_dir) ## We need to modify PATH, to find MATLAB libs if lib_dir not in os.environ['PATH']: os.environ['PATH'] = lib_dir + ';' + os.environ['PATH'] libeng = Library('libeng') libmx = Library('libmx') command = None elif system == 'Darwin': if bits == '64bit': lib_dir = join(matlab_root, "bin", "maci64") else: unsupported_platform(system, bits) check_python_matlab_architecture(bits, lib_dir) libeng = Library(join(lib_dir, 'libeng.dylib')) libmx = Library(join(lib_dir, 'libmx.dylib')) command = "{executable} {options}".format(executable=join( matlab_root, 'bin', 'matlab'), options=options) else: unsupported_platform(system, bits) ### Check MATLAB version try: version_str = c_char_p.in_dll(libeng, "libeng_version").value version = tuple([int(v) for v in version_str.split('.')[:2]]) except ValueError: warnings.warn("Unable to identify MATLAB (libeng) version.") version = None if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'): warnings.warn( "You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double." ) elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'): warnings.warn( "You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double." ) ### Start the engine engine = libeng.engOpen(command) return engine, libeng, libmx, version
#!/usr/bin/env python # This is free and unencumbered software released into the public domain. from ctypes import CDLL, c_bool, c_char_p, c_short from ctypes.util import find_library try: libmachinery = CDLL('libmachinery.so.0') except OSError: libmachinery_path = find_library('machinery') if libmachinery_path: libmachinery = CDLL(libmachinery_path) else: raise OSError('Machinery shared library not found') VERSION_STRING = c_char_p.in_dll(libmachinery, 'machinery_version_string').value VERSION_MAJOR = c_short.in_dll(libmachinery, 'machinery_version_major').value VERSION_MINOR = c_short.in_dll(libmachinery, 'machinery_version_minor').value VERSION_PATCH = c_short.in_dll(libmachinery, 'machinery_version_patch').value def version_string(): return VERSION_STRING has_feature = libmachinery.machinery_feature_exists has_feature.argtypes = [c_char_p] has_feature.restype = c_bool has_module = libmachinery.machinery_module_exists has_module.argtypes = [c_char_p] has_module.restype = c_bool if __name__ == '__main__':
from ctypes.util import find_library version_info = (0, 0, 3) __version__ = '.'.join(map(str, version_info)) __date__ = '2014-08-17' __author__ = "Marc 'BlackJack' Rintsch" __contact__ = '*****@*****.**' __license__ = 'LGPL v2.1' API_VERSION = 4 DEFAULT_CONFIG_FILENAME = '/etc/sensors3.conf' LIB_FILENAME = os.environ.get('SENSORS_LIB') or find_library('sensors') SENSORS_LIB = CDLL(LIB_FILENAME) VERSION = c_char_p.in_dll(SENSORS_LIB, 'libsensors_version').value MAJOR_VERSION = version_info[0] STDC_LIB = CDLL(find_library('c'), use_errno=True) TYPE_DICT = { 0: 'voltage', 1: 'fan', 2: 'temperature', 3: 'power', 4: 'energy', 5: 'current', 6: 'humidity', 7: 'max_main', 16: 'vid', 17: 'intrusion', 18: 'max_other',
# include from async.h type.h from ctypes import CFUNCTYPE,POINTER,Structure,c_char_p,pointer,c_long,c_voidp,c_ulong,c_int,cast,byref,c_size_t,c_void_p import ctypes from .base import lib,s_strdup,LwqqBase from .vplist import Command __all__ = [ 'Event', 'Events', 'Arguments', 'has_feature', 'version', 'VerifyCode' ] feature = c_long.in_dll(lib,"lwqq_features").value version = c_char_p.in_dll(lib, 'lwqq_version').value def has_feature(f): return feature&f class Event(LwqqBase): class T(Structure): _fields_ = [ ('result',c_int), ('failcode',c_int), ('lc',c_voidp) ] PT = POINTER(T) eventsref = [] @property def result(self): return self.ref[0].result @property def failcode(self): return self.ref[0].failcode
# Find suffix import sysconfig suffix = sysconfig.get_config_var('EXT_SUFFIX') if suffix is None: suffix = ".so" # Import shared library import os import warnings pymodulepath = os.path.dirname(__file__) from ctypes import cdll, c_char_p __libpath__ = pymodulepath + "/../librebound" + suffix clibrebound = cdll.LoadLibrary(__libpath__) # Version __version__ = c_char_p.in_dll(clibrebound, "reb_version_str").value.decode('ascii') # Build __build__ = c_char_p.in_dll(clibrebound, "reb_build_str").value.decode('ascii') # Githash __githash__ = c_char_p.in_dll(clibrebound, "reb_githash_str").value.decode('ascii') # Check for version try: moduleversion = pkg_resources.require("rebound")[0].version libreboundversion = __version__ if moduleversion != libreboundversion: warnings.warn( "WARNING: python module and librebound have different version numbers: '%s' vs '%s'.\n"
def load_engine_and_libs(matlab_root, options): """Load and return `libeng` and `libmx`. Start and return MATLAB engine. Returns ------- engine libeng libmx """ bits, linkage = platform.architecture() system = platform.system() if system == 'Linux': if bits == '64bit': lib_dir = join(matlab_root, "bin", "glnxa64") else: unsupported_platforms() libeng = Library( join(lib_dir, 'libeng.so') ) libmx = Library( join(lib_dir, 'libmx.so') ) command = "{executable} {options}".format( executable=join(matlab_root, 'bin', 'matlab'), options=options ) elif system == 'Windows': if bits == '64bit': lib_dir = join(matlab_root, "bin", "win64") else: unsupported_platforms() if lib_dir not in os.environ['PATH']: os.environ['PATH'] = lib_dir + ';' + os.environ['PATH'] libeng = Library('libeng') libmx = Library('libmx') command = None elif system == 'Darwin': if bits == '64bit': lib_dir = join(matlab_root, "bin", "maci64") else: unsupported_platforms(system,bits) libeng = Library( join(lib_dir, 'libeng.dylib') ) libmx = Library( join(lib_dir, 'libmx.dylib') ) command = "{executable} {options}".format( executable=join(matlab_root, 'bin', 'matlab'), options=options ) else: unsupported_platforms() ### Check MATLAB version try: version_str = c_char_p.in_dll(libeng, "libeng_version").value version = tuple([int(v) for v in version_str.split('.')[:2]]) except ValueError: warnings.warn("Unable to identify MATLAB version, please let us know: https://github.com/mrkrd/matlab_wrapper") if (system == 'Linux') and (version == (8,1)) and (bits == '64bit'): pass elif (system == 'Linux') and (version == (8,2)) and (bits == '64bit'): pass elif (system == 'Linux') and (version == (8,3)) and (bits == '64bit'): warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") elif (system == 'Linux') and (version == (8,4)) and (bits == '64bit'): pass elif (system == 'Windows') and (version == (8,3)) and (bits == '64bit'): pass elif (system == 'Darwin') and (version == (8,1)) and (bits == '64bit'): pass elif (system == 'Darwin') and (version == (8,3)) and (bits == '64bit'): warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") else: warnings.warn("Hi! You are using MATLAB version that was never tested with matlab_wrapper. Please, let us know about that and visit out website <https://github.com/mrkrd/matlab_wrapper> or send me an email <*****@*****.**>. Your MATLAB version is {version} on {os} with {bits}.".format(version=version_str,os=system,bits=bits)) ### Start the engine engine = libeng.engOpen(command) return engine, libeng, libmx