Ejemplo n.º 1
0
 def test_libm(self):
     system = platform.system()
     if system == "Linux":
         libm = find_library("m")
     elif system == "Darwin":
         libm = find_library("libm")
     llvm.load_library_permanently(libm)
Ejemplo n.º 2
0
def find_boost():
    """Find correct boost-python library information """
    if system == 'Linux':
        # use version suffix if present
        boost_lib = 'boost_python-py{v[0]}{v[1]}'.format(v=sys.version_info)
        if sys.version_info.major == 3:
            if find_library('boost_python-py36'):
                boost_lib = 'boost_python-py36'
            elif find_library('boost_python-py35'):
                boost_lib = 'boost_python-py35'
            elif find_library('boost_python-py34'):
                boost_lib = 'boost_python-py34'
        if not find_library(boost_lib):
            boost_lib = "boost_python"
    elif system == 'Darwin':
        boost_lib = 'boost_python-mt' if sys.version_info[0] == 2 else 'boost_python3-mt'
    elif system == 'Cygwin':
        boost_lib = 'boost_python-mt' if sys.version_info[0] == 2 else 'boost_python3-mt'
    else:
        raise Exception('Building on this system is not currently supported')

    if not find_library(boost_lib):
        raise Exception('Could not find boost python library')

    return boost_lib
Ejemplo n.º 3
0
def find_boost():
    """Find correct boost-python library information """
    # find_library() has a tricky platform-dependent search behaviour
    # it is not easy to instruct it to do search in a particular location on Linux at least
    # skip find_library checks if python comes from conda 
    # rely on conda to set up libboost_python.so link to what has been actually installed
    skip_find_library = ('conda' in sys.version)

    if system == 'Linux':
        # use version suffix if present
        boost_lib = 'boost_python-py{v[0]}{v[1]}'.format(v=sys.version_info)
        if sys.version_info.major == 3:
            for candidate in ['-py36', '-py35', '-py34', '3']:
                boost_lib = 'boost_python{}'.format(candidate)
                if find_library(boost_lib):
                    break
        if not find_library(boost_lib) or skip_find_library:
            boost_lib = "boost_python"
    elif system == 'Darwin':
        # "brew" installations of PythonBoost put lib /usr/local/lib/libboost_python27-mt resp. libboost_python36-mt
        for candidate in ['{v[0]}{v[1]}'.format(v=sys.version_info), '{}-mt'.format(sys.version_info.major)]:
            boost_lib = 'boost_python{}'.format(candidate)
            if find_library(boost_lib):
                break
        if sys.version_info.major == 2:
            boost_lib = 'boost_python-mt'
    elif system == 'Cygwin':
        boost_lib = 'boost_python-mt' if sys.version_info[0] == 2 else 'boost_python3-mt'
    else:
        raise Exception('Building on this system is not currently supported')

    if not find_library(boost_lib) and not skip_find_library:
        raise Exception('Could not find boost python library')

    return boost_lib
Ejemplo n.º 4
0
def load_cprimeslib():
	lib_path = find_library("cprimes") or find_library("libcprimes")
	lib = None

	# It's not where it should be. Maybe it's in the working directory?
	# Let's just try a bunch of names and hope for the best.
	if lib_path is None:
		names = [
			"./libcprimes.so", # Linux
			"./libcprimes.dylib", # OS X
			"./libcprimes.dll", "./cprimes.dll" # MinGW and MSVC windows, respectively
			]
		for name in names:
			# CDLL raises an exception when it cannot find the file
			# 	If it fails, move on to the next maybe name.
			# 	If not, we're done!
			try:
				lib = CDLL(name)
				break
			except:
				pass
			if lib is None:
				print("Error finding cprimes library.\nThe system couldn't find it, and it's not in the working directory.")
				sys.exit(1)
	# Python found a file with the right name, but things could still go wrong.
	else:
		try:
			lib = CDLL(lib_path)
		except OSError as e:
			print("Error finding cprimes:\n\t{}".format(e))
			sys.exit(1)

	assert(lib is not None)
	return lib
Ejemplo n.º 5
0
    def __init__(self):
        """ Find OpenMP library and try to load if using ctype interface. """
        # find_library() does not search automatically LD_LIBRARY_PATH
        paths = os.environ.get('LD_LIBRARY_PATH', '').split(':')
        for gomp in ('libgomp.so', 'libgomp.dylib'):
            cmd = [cxx, '-print-file-name=' + gomp]
            # the subprocess can fail in various ways
            # in that case just give up that path
            try:
                path = os.path.dirname(check_output(cmd).strip())
                if path:
                    paths.append(path)
            except OSError:
                pass

        # Try to load find libgomp shared library using loader search dirs
        libgomp_path = find_library("gomp")

        # Try to use custom paths if lookup failed
        for path in paths:
            if libgomp_path:
                break
            path = path.strip()
            if os.path.isdir(path):
                libgomp_path = find_library(os.path.join(path, "libgomp"))

        if not libgomp_path:
            raise ImportError("I can't find a shared library for libgomp,"
                              " you may need to install it or adjust the "
                              "LD_LIBRARY_PATH environment variable.")
        else:
            # Load the library (shouldn't fail with an absolute path right?)
            self.libomp = ctypes.CDLL(libgomp_path)
Ejemplo n.º 6
0
 def __init__(self):
     if _system == 'Darwin':
         self.libiconv = CDLL(find_library('iconv'), RTLD_GLOBAL)
     super(LibFUSE, self).__init__(find_library('fuse'))
     
     self.fuse_mount.argtypes = (c_char_p, POINTER(fuse_args))
     self.fuse_mount.restype = c_void_p
     self.fuse_lowlevel_new.argtypes = (POINTER(fuse_args), POINTER(fuse_lowlevel_ops),
                                         c_size_t, c_void_p)
     self.fuse_lowlevel_new.restype = c_void_p
     self.fuse_set_signal_handlers.argtypes = (c_void_p,)
     self.fuse_session_add_chan.argtypes = (c_void_p, c_void_p)
     self.fuse_session_loop.argtypes = (c_void_p,)
     self.fuse_remove_signal_handlers.argtypes = (c_void_p,)
     self.fuse_session_remove_chan.argtypes = (c_void_p,)
     self.fuse_session_destroy.argtypes = (c_void_p,)
     self.fuse_unmount.argtypes = (c_char_p, c_void_p)
     
     self.fuse_req_ctx.restype = POINTER(fuse_ctx)
     self.fuse_req_ctx.argtypes = (fuse_req_t,)
     
     self.fuse_reply_err.argtypes = (fuse_req_t, c_int)
     self.fuse_reply_attr.argtypes = (fuse_req_t, c_void_p, c_double)
     self.fuse_reply_entry.argtypes = (fuse_req_t, c_void_p)
     self.fuse_reply_open.argtypes = (fuse_req_t, c_void_p)
     self.fuse_reply_buf.argtypes = (fuse_req_t, c_char_p, c_size_t)
     self.fuse_reply_write.argtypes = (fuse_req_t, c_size_t)
     
     self.fuse_add_direntry.argtypes = (c_void_p, c_char_p, c_size_t, c_char_p,
                                         c_stat_p, c_off_t)
Ejemplo n.º 7
0
    def __init__(self, display=None):
        ''' GNU/Linux initialisations. '''

        if not display:
            try:
                display = environ['DISPLAY']
            except KeyError:
                raise ScreenshotError(
                    '$DISPLAY not set. Stopping to prevent segfault.')
        if not isinstance(display, bytes):
            display = bytes(display, 'utf-8')

        x11 = find_library('X11')
        if not x11:
            raise ScreenshotError('No X11 library found.')
        self.xlib = cdll.LoadLibrary(x11)

        xrandr = find_library('Xrandr')
        if not xrandr:
            raise ScreenshotError('No Xrandr extension found.')
        self.xrandr = cdll.LoadLibrary(xrandr)

        self._set_argtypes()
        self._set_restypes()

        self.display = self.xlib.XOpenDisplay(display)
        try:
            self.display.contents
        except ValueError:
            raise ScreenshotError('Cannot open display "{0}".'.format(
                str(display.decode('utf-8'))))
        self.root = self.xlib.XDefaultRootWindow(
            self.display, self.xlib.XDefaultScreen(self.display))
Ejemplo n.º 8
0
    def _find_mv_path(cls):
        if platform.system() == "Windows":
            mv_lib_path = find_library("Multiverso")
            if mv_lib_path is None:
                print "* Fail to load Multiverso.dll from the windows $PATH."\
                      "Because Multiverso.dll can not be found in the $PATH "\
                      "directories. Go on loading Multiverso from the package."
            else:
                return mv_lib_path

            mv_lib_path = os.path.join(PACKAGE_PATH, "Multiverso.dll")
            if not os.path.exists(mv_lib_path):
                print "* Fail to load Multiverso.dll from the package. Because"\
                      " the file " + mv_lib_path + " can not be found."
            else:
                return mv_lib_path
        else:
            mv_lib_path = find_library("multiverso")
            if mv_lib_path is None:
                print "* Fail to load libmultiverso.so from the system"\
                      "libraries. Because libmultiverso.so can't be found in"\
                      "library paths. Go on loading Multiverso from the package."
            else:
                return mv_lib_path

            mv_lib_path = os.path.join(PACKAGE_PATH, "libmultiverso.so")
            if not os.path.exists(mv_lib_path):
                print "* Fail to load libmultiverso.so from the package. Because"\
                      " the file " + mv_lib_path + " can not be found."
            else:
                return mv_lib_path
        return None
Ejemplo n.º 9
0
def load_librtlsdr():
    if sys.platform == "linux" and 'LD_LIBRARY_PATH' in os.environ.keys():
        ld_library_paths = [local_path for local_path in os.environ['LD_LIBRARY_PATH'].split(':') if local_path.strip()]
        driver_files = [local_path + '/librtlsdr.so' for local_path in ld_library_paths]
    else:
        driver_files = []
    driver_files += ['librtlsdr.so', 'rtlsdr/librtlsdr.so']
    driver_files += ['rtlsdr.dll', 'librtlsdr.so']
    driver_files += ['..//rtlsdr.dll', '..//librtlsdr.so']
    driver_files += ['rtlsdr//rtlsdr.dll', 'rtlsdr//librtlsdr.so']
    driver_files += [lambda : find_library('rtlsdr'), lambda : find_library('librtlsdr')]
    dll = None

    for driver in driver_files:
        if callable(driver):
            driver = driver()
        try:
            dll = CDLL(driver)
            break
        except:
            pass
    else:
        raise ImportError('Error loading librtlsdr. Make sure librtlsdr '\
                          '(and all of its dependencies) are in your path')

    return dll
Ejemplo n.º 10
0
def get_openmp_flag():
    """ Find OpenMP library and try to load if using ctype interface. """
    # find_library() does not search automatically LD_LIBRARY_PATH
    paths = os.environ.get('LD_LIBRARY_PATH', '').split(':')
    for gomp in ('libgomp.so', 'libgomp.dylib'):
        cmd = [cxx, '-print-file-name=' + gomp]
        # the subprocess can fail in various ways
        # in that case just give up that path
        try:
            path = os.path.dirname(check_output(cmd).strip())
            if path:
                paths.append(path)
        except OSError:
            pass

    # Try to load find libgomp shared library using loader search dirs
    libgomp_path = find_library("gomp")

    # Try to use custom paths if lookup failed
    for path in paths:
        if libgomp_path:
            break
        path = path.strip()
        if os.path.isdir(path):
            libgomp_path = find_library(os.path.join(path, "libgomp"))

    if not libgomp_path:
        return ''
    else:
        return '-openmp'
Ejemplo n.º 11
0
def load_librtlsdr():
    
    if platform.system() == 'Windows':
        # make sure that .DLL dependencies are accessible
        curr_path = os.path.dirname(__file__)
        os.environ['PATH']  += os.pathsep + curr_path
    
    driver_files = ['rtlsdr.dll', 'librtlsdr.so']
    driver_files += ['..//rtlsdr.dll', '..//librtlsdr.so']
    driver_files += ['rtlsdr//rtlsdr.dll', 'rtlsdr//librtlsdr.so']
    driver_files += [find_library('rtlsdr'), find_library('librtlsdr')]

    dll = None

    for driver in driver_files:
        try:
            dll = CDLL(driver)
            break
        except:
            pass
    else:
        raise ImportError('Error loading librtlsdr. Make sure librtlsdr '\
                          '(and all of its dependencies) are in your path')

    return dll
 def __init__(self, operations, mountpoint="/mnt", **kwargs):
     self.operations = operations
     
     if _system == 'Darwin':
         libiconv = CDLL(find_library("iconv"), RTLD_GLOBAL)
     libfuse = CDLL(find_library("fuse"))
     
     args = ['fuse']
     if kwargs.pop('foreground', False):
         args.append('-f')
     if kwargs.pop('debug', False):
         args.append('-d')
     if kwargs:
         args.append('-o')
         args.append(','.join(key if val == True else '%s=%s' % (key, val)
                 for key, val in kwargs.items()))
     args.append(mountpoint)
     argv = (c_char_p * len(args))(*args)
     
     fuse_ops = fuse_operations()
     for name, prototype in fuse_operations._fields_:
         method = getattr(self, name, None)
         if method:
             setattr(fuse_ops, name, prototype(method))
     
     libfuse.fuse_main_real(len(args), argv, pointer(fuse_ops), sizeof(fuse_ops), None)
Ejemplo n.º 13
0
def _init():
	"""
	Loads the shared library through ctypes and returns a library
	L{ctypes.CDLL} instance 
	"""
	dll = None
	lib = find_library('magic') or find_library('magic1')
	if lib:
		dll = ctypes.cdll.LoadLibrary(lib)
	# Following shamelessly copied from python-magic
	if (not dll) or (not dll._name):
		import sys

		lib_map = {
			'darwin' : (
				'/opt/local/lib/libmagic.dylib',
				'/usr/local/lib/libmagic.dylib',
				'/usr/local/Cellar/libmagic/5.10/lib/libmagic.dylib',
			),
			'win32' : (
				'magic1.dll',
			)
		}
		for libpath in lib_map.get(sys.platform, ()):
			try:
				dll = ctypes.cdll.LoadLibrary(libpath)
			except OSError:
				dll = None
	return dll
Ejemplo n.º 14
0
def _linux():
  platform = PLATFORM_LINUX
  
  from ctypes.util import find_library
  from os import environ
  
  bcm_name = find_library('bcm_host')
  if bcm_name:
    platform = PLATFORM_PI
    bcm = _load_library(bcm_name)
  else:
    bcm = None

  if environ.get('ANDROID_APP_PATH'):
    platform = PLATFORM_ANDROID
    opengles = _load_library('/system/lib/libGLESv2.so')
    openegl = _load_library('/system/lib/libEGL.so')
  else:
    import os
    if os.path.isfile('/opt/vc/lib/libGLESv2.so'): # raspbian
      opengles = _load_library('/opt/vc/lib/libGLESv2.so')
      openegl = _load_library('/opt/vc/lib/libEGL.so')
    elif os.path.isfile('/usr/lib/libGLESv2.so'): # ubuntu MATE (but may catch others - monitor problems)
      opengles = _load_library('/usr/lib/libGLESv2.so')
      openegl = _load_library('/usr/lib/libEGL.so')
    else:
      opengles = _load_library(find_library('GLESv2')) # has to happen first
      openegl = _load_library(find_library('EGL')) # otherwise missing symbol on pi loading egl
  
  return platform, bcm, openegl, opengles # opengles now determined by platform
Ejemplo n.º 15
0
    def __init__(self):
        ''' GNU/Linux initialisations '''

        x11 = find_library('X11')
        if not x11:
            raise ScreenshotError('MSS: no X11 library found.')
        self.xlib = cdll.LoadLibrary(x11)

        xrandr = find_library('Xrandr')
        if not xrandr:
            raise ScreenshotError('MSS: no Xrandr library found.')
        self.xrandr = cdll.LoadLibrary(xrandr)

        self._set_argtypes()
        self._set_restypes()

        disp = None
        self.display = None
        try:
            if sys.version > '3':
                disp = bytes(environ['DISPLAY'], 'utf-8')
            else:
                disp = environ['DISPLAY']
        except KeyError:
            err = 'MSS: $DISPLAY not set. Stopping to prevent segfault.'
            raise ScreenshotError(err)

        # At this point, if there is no running server, it could end on
        # a segmentation fault. And we cannot catch it.
        self.display = self.xlib.XOpenDisplay(disp)
        self.screen = self.xlib.XDefaultScreen(self.display)
        self.root = self.xlib.XDefaultRootWindow(self.display, self.screen)
Ejemplo n.º 16
0
def _find_library(name, version=0):
    """Find a library by base-name and major version
    """
    windows_names = ["%s.dll" % name, "lib%s.dll" % name,
                     "lib%s-%d.dll" % (name, version)]

    lib_file = None

    # This seems to be necessary in a bundle/dmg
    if sys.platform == "darwin":
        lib_name = '../Frameworks/lib%s.%d.dylib' % (name, version)
        if os.path.isfile(lib_name):
            lib_file = lib_name

    # force prefer current folder
    # for linux/UNIX-like and Windows
    if sys.platform in ["darwin", "cygwin"]:
        # these will already work fine with find_library
        pass
    elif sys.platform == "win32":
        for lib_name in windows_names:
            if os.path.isfile(lib_name):
                lib_file = lib_name
                break
    else:
        # that would be linux/UNIX-like
        # these need to prepend ./
        lib_name = "./lib%s.so.%d" % (name, version)
        if os.path.isfile(lib_name):
            lib_file = lib_name

    # doesn't work on Windows
    # Darwin gives a full path when found system-wide
    # Linux and Cygwin give base filename when found
    # Darwin and Cygwin will find and prefer in current folder
    if lib_file is None:
        lib_file = find_library(name)

    # Windows needs complete filenames
    # and gives a full path when found system-wide
    # also searches in current folder, but system-wide preferred
    if lib_file is None and sys.platform == "win32":
        for lib_name in windows_names:
            if lib_file is None:
                lib_file = find_library(lib_name)

    if lib_file is None:
        # this won't help anymore,
        # but gives a nice platform dependent file in the error message
        if sys.platform == "win32":
            lib_file = "%s.dll" % name
        elif sys.platform == "darwin":
            lib_file = "lib%s.%d.dylib" % (name, version)
        elif sys.platform == "cygwin":
            lib_file = "cyg%s-%d.dll" % (name, version)
        else:
            lib_file = "lib%s.so.%d" % (name, version)

    return lib_file
Ejemplo n.º 17
0
 def gather_pcap(self):
     pcap_location = ctutil.find_library('pcap')
     if(pcap_location):
         pcap = CDLL(ctutil.find_library('pcap'))
         pcap.pcap_lib_version.restype = c_char_p
         self.pcap_version = pcap.pcap_lib_version()
     else:
         self.pcap_version = "(none)"
Ejemplo n.º 18
0
def _load_crypto_libcrypto():
    from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_long, \
        Structure, c_ulong, create_string_buffer, cast
    from ctypes.util import find_library

    if sys.platform.startswith('win'):
        libcrypto = find_library('libeay32')
    else:
        libcrypto = find_library('crypto')
    if libcrypto is None:
        raise IGNOBLEError('libcrypto not found')
    libcrypto = CDLL(libcrypto)

    AES_MAXNR = 14

    c_char_pp = POINTER(c_char_p)
    c_int_p = POINTER(c_int)

    class AES_KEY(Structure):
        _fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
                    ('rounds', c_int)]
    AES_KEY_p = POINTER(AES_KEY)

    def F(restype, name, argtypes):
        func = getattr(libcrypto, name)
        func.restype = restype
        func.argtypes = argtypes
        return func

    AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
                        [c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
                         c_int])
    AES_set_decrypt_key = F(c_int, 'AES_set_decrypt_key',
                            [c_char_p, c_int, AES_KEY_p])
    AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
                        [c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
                         c_int])

    class AES(object):
        def __init__(self, userkey):
            self._blocksize = len(userkey)
            if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) :
                raise IGNOBLEError('AES improper key used')
                return
            key = self._key = AES_KEY()
            rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key)
            if rv < 0:
                raise IGNOBLEError('Failed to initialize AES key')

        def decrypt(self, data):
            out = create_string_buffer(len(data))
            iv = ("\x00" * self._blocksize)
            rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0)
            if rv == 0:
                raise IGNOBLEError('AES decryption failed')
            return out.raw

    return AES
Ejemplo n.º 19
0
def _e_path_possibilities():
    """Generator yielding possible locations of the enchant library."""
    yield os.environ.get("PYENCHANT_LIBRARY_PATH")
    yield find_library("enchant")
    yield find_library("libenchant")
    yield find_library("libenchant-1")
    if sys.platform == 'darwin':
         # enchant lib installed by macports
         yield "/opt/local/lib/libenchant.dylib"
Ejemplo n.º 20
0
 def _load_library_nix(self, version):
     library = find_library(self.library_name)
     if library is None and version is not None:
         # try to lookup with version. this is useful in linux, sometimes
         # there is'nt a libSDL.so but a libSDL-1.2.so
         library = find_library("%s-%s" % (self.library_name, version))
     if not library:
         raise ImportError, 'Dynamic library "%s" was not found' % _platform_library_name(self.library_name)
     self._dll = getattr(cdll, library)
Ejemplo n.º 21
0
Archivo: pam.py Proyecto: jfut/ganeti
  def __init__(self):
    if not c:
      raise PamRapiAuthError("ctypes Python package is not found;"
                             " remote API PAM authentication is not available")
    self.libpam = c.CDLL(util.find_library("pam"))
    if not self.libpam:
      raise PamRapiAuthError("libpam C library is not found;"
                             " remote API PAM authentication is not available")
    self.libc = c.CDLL(util.find_library("c"))
    if not self.libc:
      raise PamRapiAuthError("libc C library is not found;"
                             " remote API PAM authentication is not available")

    self.pam_acct_mgmt = self.libpam.pam_acct_mgmt
    self.pam_acct_mgmt.argtypes = [PamHandleT, c.c_int]
    self.pam_acct_mgmt.restype = c.c_int

    self.pam_authenticate = self.libpam.pam_authenticate
    self.pam_authenticate.argtypes = [PamHandleT, c.c_int]
    self.pam_authenticate.restype = c.c_int

    self.pam_end = self.libpam.pam_end
    self.pam_end.argtypes = [PamHandleT, c.c_int]
    self.pam_end.restype = c.c_int

    self.pam_get_item = self.libpam.pam_get_item
    self.pam_get_item.argtypes = [PamHandleT, c.c_int, c.POINTER(c.c_void_p)]
    self.pam_get_item.restype = c.c_int

    self.pam_putenv = self.libpam.pam_putenv
    self.pam_putenv.argtypes = [PamHandleT, c.c_char_p]
    self.pam_putenv.restype = c.c_int

    self.pam_set_item = self.libpam.pam_set_item
    self.pam_set_item.argtypes = [PamHandleT, c.c_int, c.c_void_p]
    self.pam_set_item.restype = c.c_int

    self.pam_start = self.libpam.pam_start
    self.pam_start.argtypes = [
      c.c_char_p,
      c.c_char_p,
      c.POINTER(PamConv),
      c.POINTER(PamHandleT),
      ]
    self.pam_start.restype = c.c_int

    self.calloc = self.libc.calloc
    self.calloc.argtypes = [c.c_uint, c.c_uint]
    self.calloc.restype = c.c_void_p

    self.free = self.libc.free
    self.free.argstypes = [c.c_void_p]
    self.free.restype = None

    self.strndup = self.libc.strndup
    self.strndup.argstypes = [c.c_char_p, c.c_uint]
    self.strndup.restype = c.c_char_p
Ejemplo n.º 22
0
def iter_lib(library_name):
    if not library_name:
        raise StopIteration
    if isinstance(library_name, str):
        yield library_name
        yield find_library(library_name.split('.')[0])
    else:
        for name in library_name:
            yield name
            yield find_library(name.split('.')[0])
Ejemplo n.º 23
0
Archivo: av.py Proyecto: akx/Avpy
def _version():
    
    '''
    Return libavcodec version as a tuple: lib (libav or ffmpeg), major, minor 
    and patch version
    '''

    # find_library does not support LD_LIBRARY_PATH for python < 3.4
    if 'AVPY_AVCODEC' in os.environ:
        fold, base = os.path.split(os.environ['AVPY_AVCODEC'])
        
        if 'AVPY_AVUTIL' in os.environ:
            libavutil = os.environ['AVPY_AVUTIL']
        else:
            libavutil = os.path.join(fold, re.sub('avcodec', 'avutil', base)) 

        if 'AVPY_AVRESAMPLE' in os.environ:
            libavresample = os.environ['AVPY_AVRESAMPLE']
        else:
            libavresample = os.path.join(fold, re.sub('avcodec', 'avresample', base))

        if 'AVPY_SWRESAMPLE' in os.environ:
            libswresample = os.environ['AVPY_SWRESAMPLE']
        else:
            libswresample = os.path.join(fold, re.sub('avcodec', 'swresample', base))

        libavcodec = os.environ['AVPY_AVCODEC']
    else:
        libavutil = util.find_library('avutil')
        libswresample = util.find_library('swresample')
        libavresample = util.find_library('avresample')
        libavcodec = util.find_library('avcodec')
    
    # RTD tests (debug only)
    #libavutil = None
    #libavcodec = None
    #libswresample = None
    #libavresample = None

    CDLL(libavutil, RTLD_GLOBAL)
    
    # ffmpeg have both libswresample and libavresample
    # libav only have libavresample
    if libswresample and os.path.exists(libswresample):
        lib = 'ffmpeg'
    else:
        lib = 'libav'

    # libav11
    if libavresample and os.path.exists(libavresample):
        CDLL(libavresample, RTLD_GLOBAL)
    
    version = CDLL(libavcodec, mode=RTLD_GLOBAL).avcodec_version() 

    return lib, version >> 16 & 0xFF, version >> 8 & 0xFF, version & 0xFF
Ejemplo n.º 24
0
def _load_openSSL_linux_default():
    # On Linux we use find_library() to find the OpenSSL libraries
    libcrypto_path = find_library('crypto')
    libssl_path = find_library('ssl')
    try:
        libcrypto = ctypes.CDLL(libcrypto_path, use_errno=True,use_last_error=True)
        libssl = ctypes.CDLL(libssl_path, use_errno=True, use_last_error=True)
    except OSError:
        raise ctSSLInitError('Could not load OpenSSL libraries.')
    
    return (libcrypto, libssl)   
Ejemplo n.º 25
0
def setUpModule():
    global libc_name
    if os.name == "nt":
        libc_name = find_library("c")
    elif sys.platform == "cygwin":
        libc_name = "cygwin1.dll"
    else:
        libc_name = find_library("c")

    if test.support.verbose:
        print("libc_name is", libc_name)
Ejemplo n.º 26
0
def _linux():
    platform = PLATFORM_LINUX

    from ctypes.util import find_library

    bcm_name = find_library("bcm_host")
    if bcm_name:
        platform = PLATFORM_PI
    gles_name = find_library("GLESv2")
    egl_name = find_library("EGL")

    return platform, bcm_name, gles_name, egl_name
Ejemplo n.º 27
0
def _linux():
  platform = PLATFORM_LINUX
  
  from ctypes.util import find_library
  
  bcm_name = find_library('bcm_host')
  if bcm_name:
    platform = PLATFORM_PI
  gles_name = find_library('GLESv2')
  egl_name = find_library('EGL')

  return platform, bcm_name, gles_name, egl_name
Ejemplo n.º 28
0
    def __init__(self, filename, extradlls=[], timeout=10):
        self.timeout = timeout
        self.extradlls = []
        for extradll in extradlls:
            extradll = find_library(extradll)
            self.extradlls.append(ctypes.windll.LoadLibrary(extradll))

        dllfile = find_library(filename)
        self.dll = ctypes.windll.LoadLibrary(dllfile)

        self._poll_methods = []
        self.registerPollMethods()
Ejemplo n.º 29
0
    def test_load_library(self):
        # CRT is no longer directly loadable. See issue23606 for the
        # discussion about alternative approaches.
        #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
Ejemplo n.º 30
0
def _loadLibrary():
    import platform
    system = platform.system()
    if system == 'Linux':
        dll_loader = CDLL
        path = util.find_library('haildb')
        if path is None:
            path = util.find_library('innodb')
    else:
        raise NotImplementedError('System not supported: %r' % (system, ))
    if path is None:
        raise Exception('Can\'t locate haildb/innodb library')
    return dll_loader(path, **_func_type_kw)
Ejemplo n.º 31
0
# set/get process name (using ctypes & prctl)
# set_proc_name('python rocks')
# name = get_proc_name()

import ctypes
from ctypes.util import find_library

libc = ctypes.CDLL(find_library('c'))

PR_SET_NAME = 15
PR_GET_NAME = 16


def set_proc_name(name):
    libc.prctl(PR_SET_NAME, ctypes.c_char_p(name), 0, 0, 0)


def get_proc_name():
    name = ctypes.create_string_buffer(16)
    libc.prctl(PR_GET_NAME, name, 0, 0, 0)
    return name.value
Ejemplo n.º 32
0
#!/usr/bin/env python3

import asyncio
import discord
import random
import re
from discord.ext import commands
from ctypes.util import find_library
import cogs.utils.emby_helper as emby_helper
from cogs.utils.format import *

if not discord.opus.is_loaded():
    try:
        discord.opus.load_opus('opus')
    except:
        discord.opus.load_opus(find_library('opus'))


class VoiceEntry:
    def __init__(self, message, player=None, item=None):
        self.requester = message.author
        self.channel = message.channel
        self.player = player
        self.item = item

    def __str__(self):
        fmt = '*{0.title}* by {0.uploader} and requested by {1.display_name}'
        duration = self.player.duration
        if duration:
            fmt = fmt + ' [length: {0[0]}m {0[1]}s]'.format(
                divmod(duration, 60))
            def contents(self):
                raise TypeError('This is not a ctypes pointer.')

            def __init__(self, **args):
                raise TypeError(
                    'This is not a ctypes pointer. It is not instanciable.')

        _class = type('LP_%d_%s' % (8, clsname), (_T, ), {})
        ctypes._pointer_t_type_cache[clsname] = _class
        return _class


_libraries = {}

libpulse_library_name = find_library('pulse')
if libpulse_library_name is None:
    raise Exception('No libpulse.so library found!')

try:
    _libraries['libpulse.so'] = ctypes.cdll.LoadLibrary(libpulse_library_name)
except OSError:
    raise Exception('Cannot load libpulse.so library!')

uint32_t = ctypes.c_uint32

size_t = ctypes.c_uint64


class struct_pa_context(ctypes.Structure):
    pass
Ejemplo n.º 34
0
        colorRef //= 256
        green = colorRef % 256
        colorRef //= 256
        blue = colorRef

        return (red, green, blue)

    getPixel = _winGetPixel

elif sys.platform == 'darwin':
    from rubicon.objc import ObjCClass, CGPoint
    from rubicon.objc.types import register_preferred_encoding

    #####################################################################

    appkit = cdll.LoadLibrary(util.find_library('AppKit'))

    NSEvent = ObjCClass('NSEvent')
    NSEvent.declare_class_property('mouseLocation')
    # NSSystemDefined = ObjCClass('NSSystemDefined')

    #####################################################################

    core_graphics = cdll.LoadLibrary(util.find_library('CoreGraphics'))

    CGDirectDisplayID = c_uint32

    CGEventRef = c_void_p
    register_preferred_encoding(b'^{__CGEvent=}', CGEventRef)

    CGEventSourceRef = c_void_p
Ejemplo n.º 35
0
def _resolveCtypesImports(cbinaries):
    """Completes ctypes BINARY entries for modules with their full path.
    """
    from ctypes.util import find_library

    if is_unix:
        envvar = "LD_LIBRARY_PATH"
    elif is_darwin:
        envvar = "DYLD_LIBRARY_PATH"
    else:
        envvar = "PATH"

    def _setPaths():
        path = os.pathsep.join(PyInstaller.__pathex__)
        old = compat.getenv(envvar)
        if old is not None:
            path = os.pathsep.join((path, old))
        compat.setenv(envvar, path)
        return old

    def _restorePaths(old):
        if old is None:
            compat.unsetenv(envvar)
        else:
            compat.setenv(envvar, old)

    ret = []

    # Try to locate the shared library on disk. This is done by
    # executing ctypes.utile.find_library prepending ImportTracker's
    # local paths to library search paths, then replaces original values.
    old = _setPaths()
    for cbin in cbinaries:
        # Ignore annoying warnings like:
        # 'W: library kernel32.dll required via ctypes not found'
        # 'W: library coredll.dll required via ctypes not found'
        if cbin in ['coredll.dll', 'kernel32.dll']:
            continue
        ext = os.path.splitext(cbin)[1]
        # On Windows, only .dll files can be loaded.
        if os.name == "nt" and ext.lower() in [".so", ".dylib"]:
            continue
        cpath = find_library(os.path.splitext(cbin)[0])
        if is_unix:
            # CAVEAT: find_library() is not the correct function. Ctype's
            # documentation says that it is meant to resolve only the filename
            # (as a *compiler* does) not the full path. Anyway, it works well
            # enough on Windows and Mac. On Linux, we need to implement
            # more code to find out the full path.
            if cpath is None:
                cpath = cbin
            # "man ld.so" says that we should first search LD_LIBRARY_PATH
            # and then the ldcache
            for d in compat.getenv(envvar, '').split(os.pathsep):
                if os.path.isfile(os.path.join(d, cpath)):
                    cpath = os.path.join(d, cpath)
                    break
            else:
                text = compat.exec_command("/sbin/ldconfig", "-p")
                for L in text.strip().splitlines():
                    if cpath in L:
                        cpath = L.split("=>", 1)[1].strip()
                        assert os.path.isfile(cpath)
                        break
                else:
                    cpath = None
        if cpath is None:
            logger.warn("library %s required via ctypes not found", cbin)
        else:
            ret.append((cbin, cpath, "BINARY"))
    _restorePaths(old)
    return ret
Ejemplo n.º 36
0
from ctypes import *
import sys, unittest
import os
from ctypes.util import find_library
from ctypes.test import is_resource_enabled

libc_name = None
if os.name == "nt":
    libc_name = find_library("c")
elif os.name == "ce":
    libc_name = "coredll"
elif sys.platform == "cygwin":
    libc_name = "cygwin1.dll"
else:
    libc_name = find_library("c")

if is_resource_enabled("printing"):
    print "libc_name is", libc_name


class LoaderTest(unittest.TestCase):

    unknowndll = "xxrandomnamexx"

    if libc_name is not None:

        def test_load(self):
            CDLL(libc_name)
            CDLL(os.path.basename(libc_name))
            self.assertRaises(OSError, CDLL, self.unknowndll)
Ejemplo n.º 37
0
def fc_list():
    import ctypes
    from ctypes.util import find_library

    lib = find_library('fontconfig')
    if lib is None:
        return default_font_dirs()
    try:
        lib = ctypes.CDLL(lib)
    except Exception:
        return default_font_dirs()

    prototype = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)
    try:
        get_font_dirs = prototype(('FcConfigGetFontDirs', lib))
    except (AttributeError):
        return default_font_dirs()
    prototype = ctypes.CFUNCTYPE(ctypes.c_char_p, ctypes.c_void_p)
    try:
        next_dir = prototype(('FcStrListNext', lib))
    except (AttributeError):
        return default_font_dirs()

    prototype = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
    try:
        end = prototype(('FcStrListDone', lib))
    except (AttributeError):
        return default_font_dirs()

    str_list = get_font_dirs(ctypes.c_void_p())
    if not str_list:
        return default_font_dirs()

    ans = []
    while True:
        d = next_dir(str_list)
        if not d:
            break
        if d:
            try:
                ans.append(d.decode(filesystem_encoding))
            except ValueError:
                print(f'Ignoring undecodeable font path: {d}')
                continue
    end(str_list)
    if len(ans) < 3:
        return default_font_dirs()

    parents, visited = [], set()
    for f in ans:
        path = os.path.normpath(os.path.abspath(os.path.realpath(f)))
        if path == '/':
            continue
        head, tail = os.path.split(path)
        while head and tail:
            if head in visited:
                break
            head, tail = os.path.split(head)
        else:
            parents.append(path)
            visited.add(path)
    return parents
Ejemplo n.º 38
0
from ctypes.util import find_library

from twisted.python.compat import _PY3, nativeString

if _PY3:
    # Once #6070 is implemented, this can be replaced with the implementation
    # from that ticket:
    def chr(i):
        """
        Python 3 implementation of Python 2 chr(), i.e. convert an integer to
        corresponding byte.
        """
        return bytes([i])


libc = CDLL(find_library("c"))

if sys.platform.startswith('freebsd') or sys.platform == 'darwin':
    _sockaddrCommon = [
        ("sin_len", c_uint8),
        ("sin_family", c_uint8),
    ]
else:
    _sockaddrCommon = [
        ("sin_family", c_ushort),
    ]


class in_addr(Structure):
    _fields_ = [
        ("in_addr", c_ubyte * 4),
Ejemplo n.º 39
0
        if dataCopy.get(key) == None:
            dataCopy[key] = -1
    return dataCopy

# Check if the scanned device is recognized
def isRecDev(address):
    for devAdd in recDevAddr:
        if devAdd == address:
            return True
    return False
################################################################

if not os.geteuid() == 0:
    sys.exit("script only works as root")

btlib = find_library("bluetooth")
if not btlib:
    raise Exception(
        "Can't find required bluetooth libraries"
        " (need to install bluez)"
    )
bluez = CDLL(btlib, use_errno=True)

dev_id = bluez.hci_get_route(None)

sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)
sock.bind((dev_id,))

err = bluez.hci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000);
if err < 0:
    raise Exception("Set scan parameters failed")
Ejemplo n.º 40
0
class c_utimbuf(Structure):
    _fields_ = [('actime', c_timespec), ('modtime', c_timespec)]


class c_stat(Structure):
    pass  # Platform dependent


_system = system()
_machine = machine()

_libfuse_path = os.environ.get('FUSE_LIBRARY_PATH')
if not _libfuse_path:
    if _system == 'Darwin':
        _libiconv = CDLL(find_library('iconv'),
                         RTLD_GLOBAL)  # libfuse dependency
        _libfuse_path = (find_library('fuse4x') or find_library('osxfuse')
                         or find_library('fuse'))
    else:
        _libfuse_path = find_library('fuse')

if not _libfuse_path:
    raise EnvironmentError('Unable to find libfuse')
else:
    _libfuse = CDLL(_libfuse_path)

if _system == 'Darwin' and hasattr(_libfuse, 'macfuse_version'):
    _system = 'Darwin-MacFuse'

if _system in ('Darwin', 'Darwin-MacFuse', 'FreeBSD'):
Ejemplo n.º 41
0
#
# Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]),
# Pellegrino Prevete ([email protected])  2014-2020
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
from ctypes.util import find_library
from ctypes import *
import json
import sys

# load shared library
tdjson_path = find_library('tdjson') or 'tdjson.dll'
if tdjson_path is None:
    print('can\'t find tdjson library')
    quit()
tdjson = CDLL(tdjson_path)

# load TDLib functions from shared library
td_json_client_create = tdjson.td_json_client_create
td_json_client_create.restype = c_void_p
td_json_client_create.argtypes = []

td_json_client_receive = tdjson.td_json_client_receive
td_json_client_receive.restype = c_char_p
td_json_client_receive.argtypes = [c_void_p, c_double]

td_json_client_send = tdjson.td_json_client_send
td_json_client_send.restype = None
td_json_client_send.argtypes = [c_void_p, c_char_p]
Ejemplo n.º 42
0
int TessBaseAPIRecognize(TessBaseAPI* handle, ETEXT_DESC* monitor);

void TessBaseAPISetRectangle(TessBaseAPI* handle, int left, int top, int width, int height);

char* TessBaseAPIGetUTF8Text(TessBaseAPI* handle);
void  TessDeleteText(char* text);

BOOL  TessBaseAPIDetectOrientationScript(TessBaseAPI* handle, char** best_script_name, 
                                                            int* best_orientation_deg, float* script_confidence, 
                                                            float* orientation_confidence);
""")

libtess = ffi.dlopen(PATH_TO_LIBTESS)
from ctypes.util import find_library
liblept = ffi.dlopen(find_library('lept'))

tess_version=ffi.string(libtess.TessVersion())

lep_version=ffi.string(liblept.getLeptonicaVersion())
# dawg =libtess.GlobalDawgCache()

api = libtess.TessBaseAPICreate()

# lang='eng+chi_sim'

# t0=current_milli_time()
libtess.TessBaseAPIInit3(api, data_dir, lang)
# print( "init tess in %d ms " % (current_milli_time()-t0) )

Ejemplo n.º 43
0
ISOTPSocket.
"""

import ctypes
import sys
from ctypes.util import find_library

from scapy3k.packet import *
from scapy3k.fields import *
from scapy3k.supersocket import SuperSocket
from scapy3k.sendrecv import sndrcv, sniff
from scapy3k.arch.linux import get_last_packet_timestamp, SIOCGIFINDEX
import socket

if not sys.platform.startswith("win32"):
    libc = ctypes.cdll.LoadLibrary(find_library("c"))
    warning("Loading libc with ctypes")
else:
    warning("libc is unavailable")
    libc = None
    
"""
ISOTP Packet
"""

class ISOTP(Packet):
    name = 'ISOTP'
    fields_desc = [
        StrField('data', B"")
    ]
Ejemplo n.º 44
0
    def __init__(self, handler, opts):
        _ISkypeAPIBase.__init__(self, opts)
        self.RegisterHandler(handler)

        # check options
        if opts:
            raise TypeError('Unexpected parameter(s): %s' %
                            ', '.join(opts.keys()))

        # setup Xlib
        libpath = find_library('X11')
        if not libpath:
            raise ImportError('Could not find X11 library')
        self.x11 = cdll.LoadLibrary(libpath)

        # setup Xlib function prototypes
        self.x11.XCloseDisplay.argtypes = (DisplayP, )
        self.x11.XCloseDisplay.restype = None
        self.x11.XCreateSimpleWindow.argtypes = (DisplayP, Window, c_int,
                                                 c_int, c_uint, c_uint, c_uint,
                                                 c_ulong, c_ulong)
        self.x11.XCreateSimpleWindow.restype = Window
        self.x11.XDefaultRootWindow.argtypes = (DisplayP, )
        self.x11.XDefaultRootWindow.restype = Window
        self.x11.XDeleteProperty.argtypes = (DisplayP, Window, Atom)
        self.x11.XDeleteProperty.restype = None
        self.x11.XDestroyWindow.argtypes = (DisplayP, Window)
        self.x11.XDestroyWindow.restype = None
        self.x11.XPending.argtypes = (DisplayP, )
        self.x11.XPending.restype = c_int
        self.x11.XGetAtomName.argtypes = (DisplayP, Atom)
        self.x11.XGetAtomName.restype = c_char_p
        self.x11.XGetErrorText.argtypes = (DisplayP, c_int, c_char_p, c_int)
        self.x11.XGetErrorText.restype = None
        self.x11.XGetWindowProperty.argtypes = (DisplayP, Window, Atom, c_long,
                                                c_long, Bool, Atom, AtomP,
                                                c_int_p, c_ulong_p, c_ulong_p,
                                                POINTER(POINTER(Window)))
        self.x11.XGetWindowProperty.restype = c_int
        self.x11.XInitThreads.argtypes = ()
        self.x11.XInitThreads.restype = Status
        self.x11.XInternAtom.argtypes = (DisplayP, c_char_p, Bool)
        self.x11.XInternAtom.restype = Atom
        self.x11.XNextEvent.argtypes = (DisplayP, XEventP)
        self.x11.XNextEvent.restype = None
        self.x11.XOpenDisplay.argtypes = (c_char_p, )
        self.x11.XOpenDisplay.restype = DisplayP
        self.x11.XSelectInput.argtypes = (DisplayP, Window, c_long)
        self.x11.XSelectInput.restype = None
        self.x11.XSendEvent.argtypes = (DisplayP, Window, Bool, c_long,
                                        XEventP)
        self.x11.XSendEvent.restype = Status
        self.x11.XSetErrorHandler.argtypes = (XErrorHandlerP, )
        self.x11.XSetErrorHandler.restype = None
        self.x11.XLockDisplay.argtypes = (DisplayP, )
        self.x11.XLockDisplay.restype = None
        self.x11.XUnlockDisplay.argtypes = (DisplayP, )
        self.x11.XUnlockDisplay.restype = None

        # init Xlib
        self.x11.XInitThreads()
        self.error = None
        # callback has to be saved to keep reference to bound method
        self._error_handler_callback = XErrorHandlerP(self._error_handler)
        self.x11.XSetErrorHandler(self._error_handler_callback)
        self.disp = self.x11.XOpenDisplay(None)
        if not self.disp:
            raise ISkypeAPIError('Could not open XDisplay')
        self.win_root = self.x11.XDefaultRootWindow(self.disp)
        self.win_self = self.x11.XCreateSimpleWindow(self.disp, self.win_root,
                                                     100, 100, 100, 100, 1, 0,
                                                     0)
        self.x11.XSelectInput(self.disp, self.win_root, _PropertyChangeMask)
        self.win_skype = self.get_skype()
        ctrl = 'SKYPECONTROLAPI_MESSAGE'
        self.atom_msg = self.x11.XInternAtom(self.disp, ctrl, False)
        self.atom_msg_begin = self.x11.XInternAtom(self.disp, ctrl + '_BEGIN',
                                                   False)

        self.loop_event = threading.Event()
        self.loop_timeout = 0.0001
        self.loop_break = False
Ejemplo n.º 45
0
        else:
            return ('127.0.0.1', 8333)

def connect (addr):
    addr1 = parse_addr_arg (addr)
    G.out_conn_sem.acquire (1)
    addr0 = get_my_addr (addr1)
    Connection (addr0, addr1)

def exception_notifier():
    LOG.exc()

# --- daemonize ---
# this will be in shrapnel soon.
from ctypes import cdll, util
libc = cdll.LoadLibrary (util.find_library ('libc'))

def daemonize (nochdir=1, noclose=0):
    libc.daemon (nochdir, noclose)
# -----------------

import pwd
def become (username):
    os.setuid (pwd.getpwnam(username).pw_uid)

import coro.http
import coro.backdoor
import caesure.webadmin
import zlib

def main1 (args, G):
Ejemplo n.º 46
0
    def _load_te_proteus_library(self, lib_dir_path=None):
        '''Loads the `TEProteus.dll`.'''

        if lib_dir_path is None:
            script_dir = os.path.realpath(__file__)
            script_dir = os.path.dirname(script_dir)
            lib_path = os.path.join(script_dir, 'TEProteus.dll')
            if os.path.exists(lib_path):
                lib_dir_path = script_dir

        if lib_dir_path is not None:
            libpath = os.path.join(lib_dir_path, 'TEProteus.dll')
        else:
            libpath = find_library('TEProteus.dll')
            if not libpath:
                sys32path = str('C:/Windows/System32/TEProteus.dll')
                if os.path.exists(sys32path):
                    libpath = sys32path

        teplib = ct.cdll.LoadLibrary(libpath)

        if teplib is None:
            raise Exception('failed to load TEProteus.dll')

        self._libpath = libpath
        self._teplib = teplib

        self._tep_open_inst_admin = teplib.tep_open_inst_admin
        self._tep_open_inst_admin.restype = ct.c_int
        self._tep_open_inst_admin.argtypes = None

        self._tep_close_inst_admin = teplib.tep_close_inst_admin
        self._tep_close_inst_admin.restype = ct.c_int
        self._tep_close_inst_admin.argtypes = None

        self._tep_is_inst_admin_open = teplib.tep_is_inst_admin_open
        self._tep_is_inst_admin_open.restype = ct.c_int
        self._tep_is_inst_admin_open.argtypes = None

        self._tep_get_slot_ids = teplib.tep_get_slot_ids
        self._tep_get_slot_ids.restype = ct.c_uint32
        self._tep_get_slot_ids.argtypes = [
            ndpointer(ct.c_uint32, flags="C_CONTIGUOUS"), ct.c_uint32]

        self._tep_get_slot_info = teplib.tep_get_slot_info
        self._tep_get_slot_info.restype = ct.c_int64
        self._tep_get_slot_info.argtypes = [ct.c_uint32, ]

        self._tep_get_slot_number = teplib.tep_get_slot_number
        self._tep_get_slot_number.restype = ct.c_uint16
        self._tep_get_slot_number.argtypes = [ct.c_int64, ]

        self._tep_get_slot_chassis_index = teplib.tep_get_slot_chassis_index
        self._tep_get_slot_chassis_index.restype = ct.c_uint16
        self._tep_get_slot_chassis_index.argtypes = [ct.c_int64, ]

        self._tep_get_slot_is_dummy = teplib.tep_get_slot_is_dummy
        self._tep_get_slot_is_dummy.restype = ct.c_int32
        self._tep_get_slot_is_dummy.argtypes = [ct.c_int64, ]

        self._tep_get_slot_is_in_use = teplib.tep_get_slot_is_in_use
        self._tep_get_slot_is_in_use.restype = ct.c_int32
        self._tep_get_slot_is_in_use.argtypes = [ct.c_int64, ]

        self._tep_get_slot_parent_instr_id = \
            teplib.tep_get_slot_parent_instr_id
        self._tep_get_slot_parent_instr_id.restype = ct.c_uint16
        self._tep_get_slot_parent_instr_id.argtypes = [ct.c_int64, ]

        self._tep_get_slot_fpga_version = teplib.tep_get_slot_fpga_version
        self._tep_get_slot_fpga_version.restype = ct.c_uint32
        self._tep_get_slot_fpga_version.argtypes = [ct.c_int64, ]

        self._tep_get_slot_fpga_svn = teplib.tep_get_slot_fpga_svn
        self._tep_get_slot_fpga_svn.restype = ct.c_uint32
        self._tep_get_slot_fpga_svn.argtypes = [ct.c_int64, ]

        self._tep_get_slot_fpga_date = teplib.tep_get_slot_fpga_date
        self._tep_get_slot_fpga_date.restype = ct.c_int32
        self._tep_get_slot_fpga_date.argtypes = [
            ct.c_int64,
            ct.c_char_p,
            ct.POINTER(ct.c_char),
            ct.c_uint32]

        self._tep_get_slot_idn_str = teplib.tep_get_slot_idn_str
        self._tep_get_slot_idn_str.restype = ct.c_int32
        self._tep_get_slot_idn_str.argtypes = [
            ct.c_int64,
            ct.c_char_p,
            ct.POINTER(ct.c_char),
            ct.c_uint32]

        self._tep_get_slot_fw_options = teplib.tep_get_slot_fw_options
        self._tep_get_slot_fw_options.restype = ct.c_uint32
        self._tep_get_slot_fw_options.argtypes = [ct.c_int64, ]

        self._tep_get_slot_hw_options = teplib.tep_get_slot_hw_options
        self._tep_get_slot_hw_options.restype = ct.c_uint32
        self._tep_get_slot_hw_options.argtypes = [ct.c_int64, ]

        self._tep_get_slot_installed_memory = \
            teplib.tep_get_slot_installed_memory
        self._tep_get_slot_installed_memory.restype = ct.c_uint32
        self._tep_get_slot_installed_memory.argtypes = [ct.c_int64, ]

        self._tep_open_instrument = teplib.tep_open_instrument
        self._tep_open_instrument.restype = ct.c_int64
        self._tep_open_instrument.argtypes = [ct.c_uint32, ct.c_int]

        self._tep_open_multi_slots_instrument = \
            teplib.tep_open_multi_slots_instrument
        self._tep_open_multi_slots_instrument.restype = ct.c_int64
        self._tep_open_multi_slots_instrument.argtypes = [
            ndpointer(ct.c_uint32, flags="C_CONTIGUOUS"),
            ct.c_uint32,
            ct.c_int]

        self._tep_close_instrument = teplib.tep_close_instrument
        self._tep_close_instrument.restype = ct.c_int
        self._tep_close_instrument.argtypes = [ct.c_int64, ]

        self._tep_close_all_instruments = teplib.tep_close_all_instruments
        self._tep_close_all_instruments.restype = ct.c_int
        self._tep_close_all_instruments.argtypes = None

        self._tep_get_instrument_id = teplib.tep_get_instrument_id
        self._tep_get_instrument_id.restype = ct.c_uint16
        self._tep_get_instrument_id.argtypes = [ct.c_int64, ]

        self._tep_open_comm_intf = teplib.tep_open_comm_intf
        self._tep_open_comm_intf.restype = ct.c_int64
        self._tep_open_comm_intf.argtypes = [ct.c_int64, ]

        self._tep_close_comm_intf = teplib.tep_close_comm_intf
        self._tep_close_comm_intf.restype = ct.c_int
        self._tep_close_comm_intf.argtypes = [ct.c_int64, ct.c_int64]

        self._tep_send_scpi = teplib.tep_send_scpi
        self._tep_send_scpi.restype = ct.c_int
        self._tep_send_scpi.argtypes = [
            ct.c_int64,
            ct.c_char_p,
            ct.POINTER(ct.c_char),
            ct.c_uint32]

        self._tep_write_binary_data = teplib.tep_write_binary_data
        self._tep_write_binary_data.restype = ct.c_int
        self._tep_write_binary_data.argtypes = [
            ct.c_int64,
            ct.c_char_p,
            ct.POINTER(ct.c_uint8),
            ct.c_uint64]

        self._tep_read_binary_data = teplib.tep_read_binary_data
        self._tep_read_binary_data.restype = ct.c_int
        self._tep_read_binary_data.argtypes = [
            ct.c_int64,
            ct.c_char_p,
            ct.POINTER(ct.c_uint8),
            ct.c_uint64]

        self._tep_get_write_stream_intf = teplib.tep_get_write_stream_intf
        self._tep_get_write_stream_intf.restype = ct.c_int64
        self._tep_get_write_stream_intf.argtypes = [ct.c_int64, ct.c_int]

        self._tep_get_stream_packet_size = teplib.tep_get_stream_packet_size
        self._tep_get_stream_packet_size.restype = ct.c_uint32
        self._tep_get_stream_packet_size.argtypes = None

        self._tep_is_write_stream_active = teplib.tep_is_write_stream_active
        self._tep_is_write_stream_active.restype = ct.c_int
        self._tep_is_write_stream_active.argtypes = [ct.c_int64, ]

        self._tep_get_stream_empty_buff = teplib.tep_get_stream_empty_buff
        self._tep_get_stream_empty_buff.restype = ct.POINTER(ct.c_uint8)
        self._tep_get_stream_empty_buff.argtypes = [ct.c_int64, ]

        self._tep_put_stream_full_buff = teplib.tep_put_stream_full_buff
        self._tep_put_stream_full_buff.restype = ct.c_int
        self._tep_put_stream_full_buff.argtypes = [
            ct.c_int64, ct.POINTER(ct.c_uint8), ct.c_int]

        self._tep_put_stream_empty_buff = teplib.tep_put_stream_empty_buff
        self._tep_put_stream_empty_buff.restype = ct.c_int
        self._tep_put_stream_empty_buff.argtypes = [
            ct.c_int64, ct.POINTER(ct.c_uint8)]

        self._tep_push_stream_packet = teplib.tep_push_stream_packet
        self._tep_push_stream_packet.restype = ct.c_int
        self._tep_push_stream_packet.argtypes = [
            ct.c_int64, ct.POINTER(ct.c_uint8), ct.c_int64, ct.c_int]
Ejemplo n.º 47
0
import sys
import os.path
import numpy
import copy

numpy.seterr(all="ignore")

if platform.system(
) == "Linux":  # Needed for platform.linux_distribution, which is not available on Windows and OSX
    # For Ubuntu: https://bugs.launchpad.net/ubuntu/+source/python-qt4/+bug/941826
    if platform.linux_distribution()[0] in (
            "Ubuntu",
    ):  # TODO: Needs a "if X11_GFX == 'nvidia'" here. The workaround is only needed on Ubuntu+NVidia drivers. Other drivers are not affected, but fine with this fix.
        import ctypes
        from ctypes.util import find_library
        ctypes.CDLL(find_library('GL'), ctypes.RTLD_GLOBAL)

try:
    from cura.CuraVersion import CuraVersion
except ImportError:
    CuraVersion = "master"  # [CodeStyle: Reflecting imported value]


class CuraApplication(QtApplication):
    class ResourceTypes:
        QmlFiles = Resources.UserType + 1
        Firmware = Resources.UserType + 2

    Q_ENUMS(ResourceTypes)

    def __init__(self):
Ejemplo n.º 48
0
from ctypes.util import find_library
from ctypes import (
    c_void_p,
    c_int32,
    c_char_p,
    c_size_t,
    c_byte,
    c_uint32,
    c_ulong,
    c_long,
    c_bool,
)
from ctypes import CDLL, POINTER, CFUNCTYPE


security_path = find_library("Security")
if not security_path:
    raise ImportError("The library Security could not be found")


core_foundation_path = find_library("CoreFoundation")
if not core_foundation_path:
    raise ImportError("The library CoreFoundation could not be found")


version = platform.mac_ver()[0]
version_info = tuple(map(int, version.split(".")))
if version_info < (10, 8):
    raise OSError(
        "Only OS X 10.8 and newer are supported, not %s.%s"
        % (version_info[0], version_info[1])
Ejemplo n.º 49
0
NOTEOFF events to play notes.  Instruments are defined in SoundFonts,
generally files with the extension SF2.  FluidSynth can either be used
to play audio itself, or you can call a function that returns chunks
of audio data and output the data to the soundcard yourself.
FluidSynth works on all major platforms, so pyFluidSynth should also.

"""

import time
import numpy

from ctypes import *
from ctypes.util import find_library

# Dynamically link the FluidSynth library
_fl = CDLL(find_library('fluidsynth'))


# make function prototypes a bit easier to declare
def cfunc(name, result, *args):
    """build and apply a ctypes prototype complete with parameter flags"""
    atypes = []
    aflags = []
    for arg in args:
        atypes.append(arg[1])
        aflags.append((arg[2], arg[0]) + arg[3:])
    return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags))


# Bump this up when changing the interface for users
api_version = '1.2'
Ejemplo n.º 50
0
                ('underline_position',  FT_Short),
                ('underline_thickness', FT_Short),
                ('glyph', FT_GlyphSlot), ('size', FT_Size),
                ('charmap', FT_Charmap),
                ('driver', c_void_p), ('memory', c_void_p),
                ('stream', c_void_p), ('sizes_list_head', c_void_p),
                ('sizes_list_tail', c_void_p), ('autohint', FT_Generic),
                ('extensions', c_void_p), ('internal', c_void_p)]
FT_Face = POINTER(FT_FaceRec)


##############################################################################
# __init__.py

__dll__ = None
FT_Library_filename = util.find_library('freetype')
if not FT_Library_filename and sys.platform.startswith('win'):
    fname_end = '_x64.dll' if _64_bit else '.dll'
    FT_Library_filename = load_data_file('freetype/freetype253' + fname_end)
if not FT_Library_filename:
    raise ImportError('Freetype library not found')
if not __dll__:
    __dll__ = CDLL(FT_Library_filename)


FT_Init_FreeType = __dll__.FT_Init_FreeType
FT_Done_FreeType = __dll__.FT_Done_FreeType
FT_Library_Version = __dll__.FT_Library_Version
__handle__ = None

Ejemplo n.º 51
0
from ipalib import x509 # FIXME: do not import from ipalib

from ipaplatform.constants import constants
from ipaplatform.paths import paths
from ipaplatform.redhat.authconfig import RedHatAuthConfig
from ipaplatform.base.tasks import BaseTaskNamespace

_ffi = FFI()
_ffi.cdef("""
int rpmvercmp (const char *a, const char *b);
""")

# use ctypes loader to get correct librpm.so library version according to
# https://cffi.readthedocs.org/en/latest/overview.html#id8
_librpm = _ffi.dlopen(find_library("rpm"))

log = log_mgr.get_logger(__name__)


def selinux_enabled():
    """
    Check if SELinux is enabled.
    """
    if os.path.exists(paths.SELINUXENABLED):
        try:
            ipautil.run([paths.SELINUXENABLED])
            return True
        except ipautil.CalledProcessError:
            # selinuxenabled returns 1 if not enabled
            return False
Ejemplo n.º 52
0
 def test_find(self):
     for name in ("c", "m"):
         lib = find_library(name)
         if lib:
             cdll.LoadLibrary(lib)
             CDLL(lib)
Ejemplo n.º 53
0
    def create_keychain_accessor():
        from ctypes import cdll, util, c_uint32, c_int, c_char_p, c_void_p, POINTER, pointer, byref, Structure, string_at
        lib_security = cdll.LoadLibrary(util.find_library('Security'))

        class SecKeychainAttributeInfo(Structure):
            _fields_ = [("count", c_uint32), ("tag", POINTER(c_uint32)),
                        ("format", POINTER(c_uint32))]

        class SecKeychainAttribute(Structure):
            _fields_ = [("tag", c_uint32), ("length", c_uint32),
                        ("data", c_void_p)]

        class SecKeychainAttributeList(Structure):
            _fields_ = [("count", c_uint32),
                        ("attr", POINTER(SecKeychainAttribute))]

        PtrSecKeychainAttributeList = POINTER(SecKeychainAttributeList)

        def keychain_get_credentials():
            username = settings.get('username')
            password = settings.get('password')
            if username and password:
                return (username, password)

            password_buflen = c_uint32()
            password_buf = c_void_p()
            item = c_void_p()

            error = lib_security.SecKeychainFindInternetPassword(
                None,  # keychain, NULL = default
                c_uint32(len(SERVER)),  # server name length
                c_char_p(SERVER),  # server name
                c_uint32(0),  # security domain - unused
                None,  # security domain - unused
                c_uint32(0 if not username else len(username)
                         ),  # account name length
                None if not username else c_char_p(username),  # account name
                c_uint32(0),  # path name length - unused
                None,  # path name
                c_uint32(0),  # port, 0 = any
                c_int(0),  # kSecProtocolTypeAny
                c_int(0),  # kSecAuthenticationTypeAny
                None,  # returned password length - unused
                None,  # returned password data - unused
                byref(item))  # returned keychain item reference
            if not error:
                info = SecKeychainAttributeInfo(
                    1,  # attribute count
                    pointer(c_uint32(1633903476)),  # kSecAccountItemAttr
                    pointer(c_uint32(6)))  # CSSM_DB_ATTRIBUTE_FORMAT_BLOB

                attrlist_ptr = PtrSecKeychainAttributeList()
                error = lib_security.SecKeychainItemCopyAttributesAndData(
                    item,  # keychain item reference
                    byref(info),  # list of attributes to retrieve
                    None,  # returned item class - unused
                    byref(attrlist_ptr),  # returned attribute data
                    byref(password_buflen),  # returned password length
                    byref(password_buf))  # returned password data

                if not error:
                    try:
                        if attrlist_ptr.contents.count == 1:
                            attr = attrlist_ptr.contents.attr.contents
                            username = string_at(attr.data, attr.length)
                            password = string_at(password_buf.value,
                                                 password_buflen.value)
                    finally:
                        lib_security.SecKeychainItemFreeAttributesAndData(
                            attrlist_ptr, password_buf)

            if not username or not password:
                raise MissingCredentialsException()
            else:
                return (username, password)

        return keychain_get_credentials
Ejemplo n.º 54
0
Archivo: aps.py Proyecto: BBN-Q/libaps
    def __init__(self, value):
        self._as_parameter = int(value)

    @classmethod
    def from_param(cls, obj):
        return int(obj)


APS_PY_WRAPPER_VERSION = 1.5

APS_ROOT = os.path.realpath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../'))

# load the shared library
# try with and without "lib" prefix
libpath = find_library("aps")
if libpath is None:
    libpath = find_library("libaps")
# if we still can't find it, then look in python prefix (where conda stores binaries)
if libpath is None:
    try:
        libaps = npct.load_library("libaps", libpath)
    #Finally... load it from this directory
    except OSError:
        libpath = os.path.join(APS_ROOT, 'build')
        libaps = npct.load_library("libaps", libpath)
else:
    libaps = ctypes.CDLL(libpath)

# set up argtypes and restype for functions with arguments that aren't ints or strings
libaps.set_channel_scale.argtypes = [
Ejemplo n.º 55
0
__all__ = [
    'libsvm', 'svm_problem', 'svm_parameter', 'toPyModel', 'gen_svm_nodearray',
    'print_null', 'svm_node', 'C_SVC', 'EPSILON_SVR', 'LINEAR', 'NU_SVC',
    'NU_SVR', 'ONE_CLASS', 'POLY', 'PRECOMPUTED', 'PRINT_STRING_FUN', 'RBF',
    'SIGMOID', 'c_double', 'svm_model'
]

try:
    dirname = path.dirname(path.abspath(__file__))
    if sys.platform == 'win32':
        libsvm = CDLL(path.join(dirname, r'..\windows\libsvm.dll'))
    else:
        libsvm = CDLL(path.join(dirname, '../libsvm.so.2'))
except:
    # For unix the prefix 'lib' is not considered.
    if find_library('svm'):
        libsvm = CDLL(find_library('svm'))
    elif find_library('libsvm'):
        libsvm = CDLL(find_library('libsvm'))
    else:
        raise Exception('LIBSVM library not found.')

C_SVC = 0
NU_SVC = 1
ONE_CLASS = 2
EPSILON_SVR = 3
NU_SVR = 4

LINEAR = 0
POLY = 1
RBF = 2
Ejemplo n.º 56
0
# constants adapted from C header file <pcp/pmapi.h>
from pcp.pmapi import pmErr
from cpmapi import PM_ERR_IPC

# for interfacing with libpcp - the client-side C API
from ctypes import CDLL, Structure, POINTER, cast, byref
from ctypes import c_void_p, c_char_p, c_int, c_long
from ctypes.util import find_library

##############################################################################
#
# dynamic library loads
#

LIBPCP_GUI = CDLL(find_library("pcp_gui"))
LIBC = CDLL(find_library("c"))

##############################################################################
#
# definition of structures used by C library libpcp, derived from <pcp/pmafm.h>
#


class pmRecordHost(Structure):
    """state information between the recording session and the pmlogger """
    _fields_ = [("f_config", c_void_p), ("fd_ipc", c_int),
                ("logfile", c_char_p), ("pid", c_int), ("status", c_int)]


##############################################################################
Ejemplo n.º 57
0
    from cffi import FFI

except (ImportError):
    raise FFIEngineError('Error importing cffi')

__all__ = [
    'libcrypto',
    'version',
    'version_info',
]

ffi = FFI()

ffi.cdef("const char *SSLeay_version(int type);")

libcrypto_path = find_library('crypto')
if not libcrypto_path:
    raise LibraryNotFoundError('The library libcrypto could not be found')

libcrypto = ffi.dlopen(libcrypto_path)
register_ffi(libcrypto, ffi)

version_string = ffi.string(libcrypto.SSLeay_version(0)).decode('utf-8')
version_match = re.search('\\b(\\d\\.\\d\\.\\d[a-z]*)\\b', version_string)
if not version_match:
    version_match = re.search('(?<=LibreSSL )(\\d\\.\\d(\\.\\d)?)\\b',
                              version_string)
if not version_match:
    raise LibraryNotFoundError('Error detecting the version of libcrypto')
version = version_match.group(1)
version_parts = re.sub('(\\d)([a-z]+)', '\\1.\\2', version).split('.')
Ejemplo n.º 58
0
import ctypes.util as cutil
import logging

import envi.memory as e_mem
import envi.cli as e_cli

import vtrace
import vtrace.archs.i386 as v_i386
import vtrace.archs.amd64 as v_amd64
import vtrace.platforms.base as v_base
import vtrace.platforms.posix as v_posix
import vtrace.util as v_util

logger = logging.getLogger(__name__)

libc = ctypes.CDLL(cutil.find_library("c"))
libkvm = ctypes.CDLL(cutil.find_library("kvm"))

# kvm_getprocs cmds
KERN_PROC_ALL = 0  # everything
KERN_PROC_PID = 1  # by process id
KERN_PROC_PGRP = 2  # by process group id
KERN_PROC_SESSION = 3  # by session of pid
KERN_PROC_TTY = 4  # by controlling tty
KERN_PROC_UID = 5  # by effective uid
KERN_PROC_RUID = 6  # by real uid
KERN_PROC_ARGS = 7  # get/set arguments/proctitle
KERN_PROC_PROC = 8  # only return procs
KERN_PROC_SV_NAME = 9  # get syscall vector name
KERN_PROC_RGID = 10  # by real group id
KERN_PROC_GID = 11  # by effective group id
Ejemplo n.º 59
0
def _os_uptime():
    """ Get the OS uptime. Because this is highly operating system dependent, several different
    strategies may have to be tried:"""

    try:
        # For Python 3.7 and later, most systems
        return time.clock_gettime(time.CLOCK_UPTIME)
    except AttributeError:
        pass

    try:
        # For Python 3.3 and later, most systems
        return time.clock_gettime(time.CLOCK_MONOTONIC)
    except AttributeError:
        pass

    try:
        # For Linux, Python 2 and 3:
        return float(open("/proc/uptime").read().split()[0])
    except (IOError, KeyError, OSError):
        pass

    try:
        # For MacOS, Python 2:
        from Quartz.QuartzCore import CACurrentMediaTime
        return CACurrentMediaTime()
    except ImportError:
        pass

    try:
        # for FreeBSD, Python 2
        import ctypes
        from ctypes.util import find_library

        libc = ctypes.CDLL(find_library('c'))
        size = ctypes.c_size_t()
        buf = ctypes.c_int()
        size.value = ctypes.sizeof(buf)
        libc.sysctlbyname("kern.boottime", ctypes.byref(buf),
                          ctypes.byref(size), None, 0)
        os_uptime_secs = time.time() - float(buf.value)
        return os_uptime_secs
    except (ImportError, AttributeError, IOError, NameError):
        pass

    try:
        # For OpenBSD, Python 2. See issue #428.
        import subprocess
        from datetime import datetime
        cmd = ['sysctl', 'kern.boottime']
        proc = subprocess.Popen(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        o, e = proc.communicate()
        # Check for errors
        if e:
            raise IOError
        time_t = o.decode('ascii').split()
        time_as_string = time_t[1] + " " + time_t[2] + " " + time_t[
            4][:4] + " " + time_t[3]
        os_time = datetime.strptime(time_as_string, "%b %d %Y %H:%M:%S")
        epoch_time = (os_time - datetime(1970, 1, 1)).total_seconds()
        os_uptime_secs = time.time() - epoch_time
        return os_uptime_secs
    except (IOError, IndexError, ValueError):
        pass

    # Nothing seems to be working. Return None
    return None
Ejemplo n.º 60
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
if sys.platform == "linux" or sys.platform == "linux2":
    # TODO remove this OpenGL fix when PyQt
    # doesn't require OpenGL to be loaded first.
    # NOTE This must be placed before any other imports!
    import ctypes
    from ctypes.util import find_library
    libGL = find_library("GL")
    ctypes.CDLL(libGL, ctypes.RTLD_GLOBAL)

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtQml import *
from PyQt5.QtWidgets import *
import qml_qrc


def main():
    app = QApplication(sys.argv)

    engine = QQmlApplicationEngine()
    engine.load(QUrl("qrc:/main.qml"))

    return app.exec_()


if __name__ == "__main__":
    sys.exit(main())