Python ctypes.util() Examples

The following are 30 code examples of ctypes.util(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: cet.py    From libcet with MIT License 7 votes vote down vote up
def __init__(self, ticket_number_key, request_data_key,
                 libcrypto_path=None):
        self.check_des_key(ticket_number_key)
        self.check_des_key(request_data_key)

        self.ticket_number_key = ticket_number_key
        self.request_data_key = request_data_key

        if not libcrypto_path:
            from ctypes.util import find_library
            libcrypto_path = find_library('crypto')
            if not libcrypto_path:
                raise Exception('libcrypto(OpenSSL) not found')

        self.libcrypto = ctypes.CDLL(libcrypto_path)

        if hasattr(self.libcrypto, 'OpenSSL_add_all_ciphers'):
            self.libcrypto.OpenSSL_add_all_ciphers() 
Example #2
Source File: __init__.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def forget(modname):
    """'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    """
    unload(modname)
    for dirname in sys.path:
        source = os.path.join(dirname, modname + '.py')
        # It doesn't matter if they exist or not, unlink all possible
        # combinations of PEP 3147/488 and legacy pyc files.
        unlink(source + 'c')
        for opt in ('', 1, 2):
            unlink(importlib.util.cache_from_source(source, optimization=opt))

# Check whether a gui is actually available 
Example #3
Source File: lib.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def find_library(self, path):

        # search first for local libs
        if _local_lib_paths:
            if not self._local_libs_cache:
                self._local_libs_cache = self._find_libs(_local_lib_paths)
            if path in self._local_libs_cache:
                return self._local_libs_cache[path]

        # ctypes tries ldconfig, gcc and objdump.  If none of these are
        # present, we implement the ld-linux.so search path as described in
        # the man page.

        result = ctypes.util.find_library(path)

        if result:
            return result

        if self._ld_so_cache is None:
            self._create_ld_so_cache()

        return self._ld_so_cache.get(path) 
Example #4
Source File: inotify_c.py    From hacker-scripts with MIT License 6 votes vote down vote up
def _load_libc():
    libc_path = None
    try:
        libc_path = ctypes.util.find_library('c')
    except (OSError, IOError):
        # Note: find_library will on some platforms raise these undocumented
        # errors, e.g.on android IOError "No usable temporary directory found"
        # will be raised.
        pass

    if libc_path is not None:
        return ctypes.CDLL(libc_path)

    # Fallbacks
    try:
        return ctypes.CDLL('libc.so')
    except (OSError, IOError):
        return ctypes.CDLL('libc.so.6') 
Example #5
Source File: key_names.py    From kitty with GNU General Public License v3.0 6 votes vote down vote up
def load_libxkb_lookup() -> LookupFunc:
        import ctypes
        for suffix in ('.0', ''):
            with suppress(Exception):
                lib = ctypes.CDLL('libxkbcommon.so' + suffix)
                break
        else:
            from ctypes.util import find_library
            lname = find_library('xkbcommon')
            if lname is None:
                raise RuntimeError('Failed to find libxkbcommon')
            lib = ctypes.CDLL(lname)

        f = lib.xkb_keysym_from_name
        f.argtypes = [ctypes.c_char_p, ctypes.c_int]
        f.restype = ctypes.c_int

        def xkb_lookup(name: str, case_sensitive: bool = False) -> Optional[int]:
            q = name.encode('utf-8')
            return f(q, int(case_sensitive)) or None

        return xkb_lookup 
Example #6
Source File: system.py    From stem with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _set_proc_title(process_name: str) -> None:
  """
  BSD specific calls (should be compataible with both FreeBSD and OpenBSD:
  http://fxr.watson.org/fxr/source/gen/setproctitle.c?v=FREEBSD-LIBC
  http://www.rootr.net/man/man/setproctitle/3
  """

  libc = ctypes.CDLL(ctypes.util.find_library('c'))
  name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
  name_buffer.value = process_name.encode()

  try:
    libc.setproctitle(ctypes.byref(name_buffer))
  except AttributeError:
    # Possible issue (seen on OSX):
    # AttributeError: dlsym(0x7fff6a41d1e0, setproctitle): symbol not found

    pass 
Example #7
Source File: __init__.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def forget(modname):
    """'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147 or
    legacy .pyc and .pyo files.
    """
    unload(modname)
    for dirname in sys.path:
        source = os.path.join(dirname, modname + '.py')
        # It doesn't matter if they exist or not, unlink all possible
        # combinations of PEP 3147 and legacy pyc and pyo files.
        unlink(source + 'c')
        unlink(source + 'o')
        unlink(importlib.util.cache_from_source(source, debug_override=True))
        unlink(importlib.util.cache_from_source(source, debug_override=False))

# Check whether a gui is actually available 
Example #8
Source File: test_android.py    From chaquopy with MIT License 6 votes vote down vote up
def test_ctypes(self):
        from ctypes.util import find_library
        libc = ctypes.CDLL(find_library("c"))
        liblog = ctypes.CDLL(find_library("log"))
        self.assertIsNone(find_library("nonexistent"))

        # Work around double-underscore mangling of __android_log_write.
        def assertHasSymbol(dll, name):
            self.assertIsNotNone(getattr(dll, name))
        def assertNotHasSymbol(dll, name):
            with self.assertRaises(AttributeError):
                getattr(dll, name)

        assertHasSymbol(libc, "printf")
        assertHasSymbol(liblog, "__android_log_write")
        assertNotHasSymbol(libc, "__android_log_write")

        # Global search (https://bugs.python.org/issue34592): only works on newer API levels.
        if API_LEVEL >= 21:
            main = ctypes.CDLL(None)
            assertHasSymbol(main, "printf")
            assertHasSymbol(main, "__android_log_write")
            assertNotHasSymbol(main, "nonexistent")

        assertHasSymbol(ctypes.pythonapi, "PyObject_Str") 
Example #9
Source File: inotify_c.py    From script.service.kodi.callbacks with GNU General Public License v3.0 6 votes vote down vote up
def _load_libc():
    libc_path = None
    try:
        libc_path = ctypes.util.find_library('c')
    except (OSError, IOError):
        # Note: find_library will on some platforms raise these undocumented
        # errors, e.g.on android IOError "No usable temporary directory found"
        # will be raised.
        pass

    if libc_path is not None:
        return ctypes.CDLL(libc_path)

    # Fallbacks
    try:
        return ctypes.CDLL('libc.so')
    except (OSError, IOError):
        return ctypes.CDLL('libc.so.6') 
Example #10
Source File: __init__.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def forget(modname):
    """'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    """
    unload(modname)
    for dirname in sys.path:
        source = os.path.join(dirname, modname + '.py')
        # It doesn't matter if they exist or not, unlink all possible
        # combinations of PEP 3147/488 and legacy pyc files.
        unlink(source + 'c')
        for opt in ('', 1, 2):
            unlink(importlib.util.cache_from_source(source, optimization=opt))

# Check whether a gui is actually available 
Example #11
Source File: threads.py    From biggraphite with Apache License 2.0 5 votes vote down vote up
def set_thread_names():
    """Expose python thread names."""
    libpthread_path = ctypes.util.find_library("pthread")
    if not libpthread_path:
        return
    libpthread = ctypes.CDLL(libpthread_path)
    if hasattr(libpthread, "pthread_setname_np"):
        pthread_setname_np = libpthread.pthread_setname_np
        pthread_setname_np.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
        pthread_setname_np.restype = ctypes.c_int
        orig_start = threading.Thread.start

        def new_start(self):
            orig_start(self)
            try:
                name = self.name
                if not name or name.startswith("Thread-"):
                    name = self.__class__.__name__
                    if name == "Thread":
                        name = self.name
                if name:
                    if isinstance(name, six.text_type):
                        name = name.encode("ascii", "replace")
                    ident = getattr(self, "ident", None)
                    if ident is not None:
                        pthread_setname_np(ident, name[:15])
            except Exception:
                pass  # Don't care about failure to set name

        threading.Thread.start = new_start 
Example #12
Source File: library.py    From PyEasyArchive with GNU General Public License v2.0 5 votes vote down vote up
def find_and_load_library():
    search_filepaths = []

    # Search for the library using our own environment variable.

    filepath = os.environ.get('LA_LIBRARY_FILEPATH', '')
    if filepath != '':
        search_filepaths.append(filepath)

    # Search for the library using the well-defined system library search-path.

    _SEARCH_PATH = os.environ.get('LD_LIBRARY_PATH', '')
    if _SEARCH_PATH != '':
        for path in _SEARCH_PATH.split(":"):
            filepath = os.path.join(path, _LIBRARY_FILENAME)
            search_filepaths.append(filepath)

    # Search for our library using whatever search-path ctypes uses (not the same 
    # as `LD_LIBRARY_PATH`).

    filepath = ctypes.util.find_library(_LIBRARY_NAME)
    if filepath is not None:
        search_filepaths.append(filepath)

    # Load the first one available.

    found_filepath = None
    for filepath in search_filepaths:
        if os.path.exists(filepath) is True:
            return filepath

    # Fallback on the naively trying to load the filename.

    _LOGGER.debug("Using default library file-path: [%s]", _LIBRARY_FILENAME)
    return _LIBRARY_FILENAME 
Example #13
Source File: systemtime.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def set_datetime(ut=0):
    """
    Set system time from provided Unix timestamp (or current time via NTP).

    :param int ut: Unix timestamp
    """
    ut = int(ut) if ut else int(get_idatetime())
    librt = ctypes.CDLL(ctypes.util.find_library("rt"), use_errno=True)
    ts = timespec()
    ts.tv_sec, ts.tv_nsec = ut, 0
    res = librt.clock_settime(0, ctypes.byref(ts))
    if res == -1:
        raise errors.OperationFailedError(
            "Could not set time: {0}".format(os.strerror(ctypes.get_errno())))
    signals.emit("config", "time_changed", ut) 
Example #14
Source File: test_reusable_executor.py    From loky with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def kill_friend(pid, delay=0):
    """Function that send SIGKILL at process pid"""
    sleep(delay)
    try:
        os.kill(pid, SIGKILL)
    except (PermissionError, ProcessLookupError) as e:
        if psutil.pid_exists(pid):
            util.debug("Fail to kill an alive process?!?")
            raise e
        util.debug("process {} was already dead".format(pid)) 
Example #15
Source File: common.py    From vehicle-triplet-reid with MIT License 5 votes vote down vote up
def __init__(self, stream=None):
        logging.StreamHandler.__init__(self, stream)
        # get file handle for the stream
        import ctypes, ctypes.util
        # for some reason find_msvcrt() sometimes doesn't find msvcrt.dll on my system?
        crtname = ctypes.util.find_msvcrt()
        if not crtname:
            crtname = ctypes.util.find_library("msvcrt")
        crtlib = ctypes.cdll.LoadLibrary(crtname)
        self._outhdl = crtlib._get_osfhandle(self.stream.fileno()) 
Example #16
Source File: openssl.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def load_opensll_dll():
    # path = os.getcwd() + '/libeay32.dll'
    path = os.getcwd()
    if platform.architecture()[0] == '64bit':
        path += '/microchat/ecdh/x64/libeay32.dll'
    else:
        path += '/microchat/ecdh/x86/libeay32.dll'
    libname = ctypes.util.find_library(path)
    if libname is None:
        raise Exception("Couldn't load OpenSSL lib ...")
    return libname 
Example #17
Source File: __init__.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def make_legacy_pyc(source):
    """Move a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    """
    pyc_file = importlib.util.cache_from_source(source)
    up_one = os.path.dirname(os.path.abspath(source))
    legacy_pyc = os.path.join(up_one, source + 'c')
    os.rename(pyc_file, legacy_pyc)
    return legacy_pyc 
Example #18
Source File: common.py    From triplet-reid with MIT License 5 votes vote down vote up
def __init__(self, stream=None):
        logging.StreamHandler.__init__(self, stream)
        # get file handle for the stream
        import ctypes, ctypes.util
        # for some reason find_msvcrt() sometimes doesn't find msvcrt.dll on my system?
        crtname = ctypes.util.find_msvcrt()
        if not crtname:
            crtname = ctypes.util.find_library("msvcrt")
        crtlib = ctypes.cdll.LoadLibrary(crtname)
        self._outhdl = crtlib._get_osfhandle(self.stream.fileno()) 
Example #19
Source File: lib.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_library(self, name):
        return ctypes.util.find_library(name) 
Example #20
Source File: _nixmouse.py    From mouse with MIT License 5 votes vote down vote up
def build_display():
    global display, window, x11
    if display and window and x11: return
    x11 = ctypes.cdll.LoadLibrary(ctypes.util.find_library('X11'))
    # Required because we will have multiple threads calling x11,
    # such as the listener thread and then main using "move_to".
    x11.XInitThreads()
    # Explicitly set XOpenDisplay.restype to avoid segfault on 64 bit OS.
    # http://stackoverflow.com/questions/35137007/get-mouse-position-on-linux-pure-python
    x11.XOpenDisplay.restype = c_void_p
    display = c_void_p(x11.XOpenDisplay(0))
    window = x11.XDefaultRootWindow(display) 
Example #21
Source File: rabinpoly.py    From librabinpoly with GNU General Public License v2.0 5 votes vote down vote up
def getpaths(self,libname):
        """Return a list of paths where the library might be found."""
        if os.path.isabs(libname):
            yield libname
        else:
            # FIXME / TODO return '.' and os.path.dirname(__file__)
            for path in self.getplatformpaths(libname):
                yield path

            path = ctypes.util.find_library(libname)
            if path: yield path 
Example #22
Source File: rabinpoly.py    From librabinpoly with GNU General Public License v2.0 5 votes vote down vote up
def getplatformpaths(self, libname):
        if self._ld_so_cache is None:
            self._create_ld_so_cache()

        result = self._ld_so_cache.get(libname)
        if result: yield result

        path = ctypes.util.find_library(libname)
        if path: yield os.path.join("/lib",path)

# Windows 
Example #23
Source File: py2.py    From pypxlib with GNU General Public License v2.0 5 votes vote down vote up
def getplatformpaths(self, libname):
        if self._ld_so_cache is None:
            self._create_ld_so_cache()

        result = self._ld_so_cache.get(libname)
        if result: yield result

        path = ctypes.util.find_library(libname)
        if path: yield os.path.join("/lib",path)

# Windows 
Example #24
Source File: py2.py    From pypxlib with GNU General Public License v2.0 5 votes vote down vote up
def getpaths(self,libname):
        """Return a list of paths where the library might be found."""
        if os.path.isabs(libname):
            yield libname
        else:
            # FIXME / TODO return '.' and os.path.dirname(__file__)
            for path in self.getplatformpaths(libname):
                yield path

            path = ctypes.util.find_library(libname)
            if path: yield path 
Example #25
Source File: py3.py    From pypxlib with GNU General Public License v2.0 5 votes vote down vote up
def getplatformpaths(self, libname):
        if os.path.sep not in libname:
            for name in self.name_formats:
                yield os.path.abspath(name % libname)
                yield os.path.join(os.path.dirname(__file__), name % libname)
                path = ctypes.util.find_library(name % libname)
                if path:
                    yield path

# Platform switching

# If your value of sys.platform does not appear in this dict, please contact
# the Ctypesgen maintainers. 
Example #26
Source File: py3.py    From pypxlib with GNU General Public License v2.0 5 votes vote down vote up
def getplatformpaths(self, libname):
        if self._ld_so_cache is None:
            self._create_ld_so_cache()

        result = self._ld_so_cache.get(libname)
        if result: yield result

        path = ctypes.util.find_library(libname)
        if path: yield os.path.join("/lib",path)

# Windows 
Example #27
Source File: py3.py    From pypxlib with GNU General Public License v2.0 5 votes vote down vote up
def getpaths(self,libname):
        """Return a list of paths where the library might be found."""
        if os.path.isabs(libname):
            yield libname
        else:
            # FIXME / TODO return '.' and os.path.dirname(__file__)
            for path in self.getplatformpaths(libname):
                yield path

            path = ctypes.util.find_library(libname)
            if path: yield path 
Example #28
Source File: rabinpoly.py    From librabinpoly with GNU General Public License v2.0 5 votes vote down vote up
def getplatformpaths(self, libname):
        if os.path.sep not in libname:
            for name in self.name_formats:
                dll_in_current_dir = os.path.abspath(name % libname)
                if os.path.exists(dll_in_current_dir):
                    yield dll_in_current_dir
                path = ctypes.util.find_library(name % libname)
                if path:
                    yield path

# Platform switching

# If your value of sys.platform does not appear in this dict, please contact
# the Ctypesgen maintainers. 
Example #29
Source File: __init__.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def make_legacy_pyc(source):
    """Move a PEP 3147 pyc/pyo file to its legacy pyc/pyo location.

    The choice of .pyc or .pyo extension is done based on the __debug__ flag
    value.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    """
    pyc_file = importlib.util.cache_from_source(source)
    up_one = os.path.dirname(os.path.abspath(source))
    legacy_pyc = os.path.join(up_one, source + ('c' if __debug__ else 'o'))
    os.rename(pyc_file, legacy_pyc)
    return legacy_pyc 
Example #30
Source File: test_android.py    From chaquopy with MIT License 5 votes vote down vote up
def setUp(self):
        from android.util import Log
        Log.i(*self.get_marker())
        self.expected_log = []