Python ctypes 模块,util() 实例源码

我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用ctypes.util()

项目:code    作者:ActiveState    | 项目源码 | 文件源码
def get_ctypes_strsignal():
        """Strategy 1: If the C library exposes strsignal(), use it."""
        import signal
        import ctypes
        import ctypes.util
        libc = ctypes.CDLL(ctypes.util.find_library("c"))
        strsignal_proto = ctypes.CFUNCTYPE(ctypes.c_char_p,
                                           ctypes.c_int)
        strsignal_c = strsignal_proto(("strsignal", libc), ((1,),))
        NSIG = signal.NSIG
        def strsignal_ctypes_wrapper(signo):
            # The behavior of the C library strsignal() is unspecified if
            # called with an out-of-range argument.  Range-check on entry
            # _and_ NULL-check on exit.
            if 0 <= signo < NSIG:
                s = strsignal_c(signo)
                if s:
                    return s.decode("utf-8")
            return "Unknown signal "+str(signo)

        return strsignal_ctypes_wrapper
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def openLibrary():
    import ctypes
    import ctypes.util
    try:
        if sys.platform.startswith("win"):
            dll_path = "src/lib/opensslVerify/libeay32.dll"
        elif sys.platform == "cygwin":
            dll_path = "/bin/cygcrypto-1.0.0.dll"
        else:
            dll_path = "/usr/local/ssl/lib/libcrypto.so"
        ssl = ctypes.CDLL(dll_path, ctypes.RTLD_GLOBAL)
        assert ssl
    except:
        dll_path = ctypes.util.find_library('ssl') or ctypes.util.find_library('crypto') or ctypes.util.find_library('libcrypto')
        ssl = ctypes.CDLL(dll_path or 'libeay32', ctypes.RTLD_GLOBAL)
    return ssl
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def openssl_set_session_cache_mode(context, mode):
    assert isinstance(context, OpenSSL.SSL.Context)
    try:
        import ctypes
        SSL_CTRL_SET_SESS_CACHE_MODE = 44
        SESS_CACHE_OFF = 0x0
        SESS_CACHE_CLIENT = 0x1
        SESS_CACHE_SERVER = 0x2
        SESS_CACHE_BOTH = 0x3
        c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
        if hasattr(context, 'set_session_cache_mode'):
            context.set_session_cache_mode(c_mode)
        elif OpenSSL.__version__ == '0.13':
            # http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
            c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
            if os.name == 'nt':
                # https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
                ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
            else:
                import ctypes.util
                # FIXME
                # ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
    except Exception as e:
        logging.warning('openssl_set_session_cache_mode failed: %r', e)
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def skip_if_lib_missing(libname, text=None):
    """
    pytest decorator to evaluate the required shared lib.

    :param libname: Name of the required library.
    :param text: Text to put into the reason message
                 (defaults to 'lib%s.so' % libname)

    :return: pytest decorator with a reason.
    """
    soname = ctypes.util.find_library(libname)
    if not text:
        text = "lib%s.so" % libname
    # Return pytest decorator.
    return skipif(not (soname and ctypes.CDLL(soname)),
                  reason="required %s missing" % text)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
项目:siphon-cli    作者:getsiphon    | 项目源码 | 文件源码
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')
项目:FightstickDisplay    作者:calexil    | 项目源码 | 文件源码
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)
项目:PyCS    作者:COSMOGRAIL    | 项目源码 | 文件源码
def nprocessors():
  try:
    try:
      # Mac OS
      libc=ctypes.cdll.LoadLibrary(ctypes.util.find_library('libc'))
      v=ctypes.c_int(0)
      size=ctypes.c_size_t(ctypes.sizeof(v))
      libc.sysctlbyname('hw.ncpu', ctypes.c_voidp(ctypes.addressof(v)), ctypes.addressof(size), None, 0)
      return v.value
    except:
      # Cygwin (Windows) and Linuxes
      # Could try sysconf(_SC_NPROCESSORS_ONLN) (LSB) next.  Instead, count processors in cpuinfo.
      s = open('/proc/cpuinfo', 'r').read()
      return s.replace(' ', '').replace('\t', '').count('processor:')
  except:
    return 1
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def openssl_set_session_cache_mode(context, mode):
    assert isinstance(context, OpenSSL.SSL.Context)
    try:
        import ctypes
        SSL_CTRL_SET_SESS_CACHE_MODE = 44
        SESS_CACHE_OFF = 0x0
        SESS_CACHE_CLIENT = 0x1
        SESS_CACHE_SERVER = 0x2
        SESS_CACHE_BOTH = 0x3
        c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
        if hasattr(context, 'set_session_cache_mode'):
            context.set_session_cache_mode(c_mode)
        elif OpenSSL.__version__ == '0.13':
            # http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
            c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
            if os.name == 'nt':
                # https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
                ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
            else:
                import ctypes.util
                # FIXME
                # ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
    except Exception as e:
        logging.warning('openssl_set_session_cache_mode failed: %r', e)
项目:cryptogram    作者:xinmingzhang    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:download-npo    作者:Carpetsmoker    | 项目源码 | 文件源码
def __init__(self, url):
        self.libmms = ctypes.cdll.LoadLibrary(ctypes.util.find_library('mms'))
        if self.libmms._name is None:  # pylint:disable=protected-access
            raise download_npo.Error(
                'Deze video is in het (oude) MMS/WMV formaat; om dit te'
                'downloaden heb je libmms nodig, welke niet is gevonden op je'
                'systeem. Zie: http://sourceforge.net/projects/libmms/')

        self._libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))

        mmsh_connect = self.libmms.mmsh_connect
        mmsh_connect.restype = ctypes.POINTER(mmsh_t)

        if sys.version_info[0] > 2:
            url = bytes(url, 'utf-8')

        self._mms = mmsh_connect(None, None, url, 128 * 1024)

        malloc = self._libc.malloc
        malloc.restype = ctypes.POINTER(ctypes.c_char)
        self.buf = malloc(8192)
项目:UMOG    作者:hsab    | 项目源码 | 文件源码
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)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
def _dnn_lib():
    if _dnn_lib.handle is None:
        import ctypes.util

        lib_name = ctypes.util.find_library('cudnn')
        if lib_name is None and sys.platform == 'win32':
            # Update these names when new versions of cudnn are supported.
            for name in ['cudnn64_5.dll', 'cudnn64_4.dll']:
                lib_name = ctypes.util.find_library(name)
                if lib_name:
                    break
        if lib_name is None:
            raise RuntimeError('Could not find cudnn library (looked for v4 and v5[.1])')
        _dnn_lib.handle = ctypes.cdll.LoadLibrary(lib_name)
        cudnn = _dnn_lib.handle
        cudnn.cudnnCreate.argtypes = [ctypes.POINTER(ctypes.c_void_p)]
        cudnn.cudnnCreate.restype = ctypes.c_int
        cudnn.cudnnDestroy.argtypes = [ctypes.c_void_p]
        cudnn.cudnnDestroy.restype = ctypes.c_int
    return _dnn_lib.handle
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
项目:hacker-scripts    作者:restran    | 项目源码 | 文件源码
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')
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def openssl_set_session_cache_mode(context, mode):
    assert isinstance(context, OpenSSL.SSL.Context)
    try:
        import ctypes
        SSL_CTRL_SET_SESS_CACHE_MODE = 44
        SESS_CACHE_OFF = 0x0
        SESS_CACHE_CLIENT = 0x1
        SESS_CACHE_SERVER = 0x2
        SESS_CACHE_BOTH = 0x3
        c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
        if hasattr(context, 'set_session_cache_mode'):
            context.set_session_cache_mode(c_mode)
        elif OpenSSL.__version__ == '0.13':
            # http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
            c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
            if os.name == 'nt':
                # https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
                ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
            else:
                import ctypes.util
                # FIXME
                # ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
    except Exception as e:
        logging.warning('openssl_set_session_cache_mode failed: %r', e)
项目:mac-package-build    作者:persepolisdm    | 项目源码 | 文件源码
def skip_if_lib_missing(libname, text=None):
    """
    pytest decorator to evaluate the required shared lib.

    :param libname: Name of the required library.
    :param text: Text to put into the reason message
                 (defaults to 'lib%s.so' % libname)

    :return: pytest decorator with a reason.
    """
    soname = ctypes.util.find_library(libname)
    if not text:
        text = "lib%s.so" % libname
    # Return pytest decorator.
    return skipif(not (soname and ctypes.CDLL(soname)),
                  reason="required %s missing" % text)
项目:Proxy-Factory    作者:ping99    | 项目源码 | 文件源码
def openssl_set_session_cache_mode(context, mode):
    assert isinstance(context, OpenSSL.SSL.Context)
    try:
        import ctypes
        SSL_CTRL_SET_SESS_CACHE_MODE = 44
        SESS_CACHE_OFF = 0x0
        SESS_CACHE_CLIENT = 0x1
        SESS_CACHE_SERVER = 0x2
        SESS_CACHE_BOTH = 0x3
        c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
        if hasattr(context, 'set_session_cache_mode'):
            context.set_session_cache_mode(c_mode)
        elif OpenSSL.__version__ == '0.13':
            # http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
            c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
            if os.name == 'nt':
                # https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
                ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
            else:
                import ctypes.util
                # FIXME
                # ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
    except Exception as e:
        logging.warning('openssl_set_session_cache_mode failed: %r', e)
项目:Proxy-Factory    作者:ping99    | 项目源码 | 文件源码
def openssl_set_session_cache_mode(context, mode):
    assert isinstance(context, OpenSSL.SSL.Context)
    try:
        import ctypes
        SSL_CTRL_SET_SESS_CACHE_MODE = 44
        SESS_CACHE_OFF = 0x0
        SESS_CACHE_CLIENT = 0x1
        SESS_CACHE_SERVER = 0x2
        SESS_CACHE_BOTH = 0x3
        c_mode = {'off':SESS_CACHE_OFF, 'client':SESS_CACHE_CLIENT, 'server':SESS_CACHE_SERVER, 'both':SESS_CACHE_BOTH}[mode.lower()]
        if hasattr(context, 'set_session_cache_mode'):
            context.set_session_cache_mode(c_mode)
        elif OpenSSL.__version__ == '0.13':
            # http://bazaar.launchpad.net/~exarkun/pyopenssl/release-0.13/view/head:/OpenSSL/ssl/context.h#L27
            c_context = ctypes.c_void_p.from_address(id(context)+ctypes.sizeof(ctypes.c_int)+ctypes.sizeof(ctypes.c_voidp))
            if os.name == 'nt':
                # https://github.com/openssl/openssl/blob/92c78463720f71e47c251ffa58493e32cd793e13/ssl/ssl.h#L884
                ctypes.c_int.from_address(c_context.value+ctypes.sizeof(ctypes.c_voidp)*7+ctypes.sizeof(ctypes.c_ulong)).value = c_mode
            else:
                import ctypes.util
                # FIXME
                # ctypes.cdll.LoadLibrary(ctypes.util.find_library('ssl')).SSL_CTX_ctrl(c_context, SSL_CTRL_SET_SESS_CACHE_MODE, c_mode, None)
    except Exception as e:
        logging.warning('openssl_set_session_cache_mode failed: %r', e)
项目:Daniel-Arbuckles-Mastering-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def load_library(*alternates):
    for base_name in alternates:
        lib_name = ctypes.util.find_library(base_name)

        try:
            if lib_name:
                return ctypes.CDLL(lib_name)
            else:
                return ctypes.CDLL(base_name)
        except OSError:
            pass

    raise OSError('Unable to load any of: {}'.format(alternates))
项目:ipwndfu    作者:axi0mX    | 项目源码 | 文件源码
def locate_library (candidates, find_library=ctypes.util.find_library):
    """Tries to locate a library listed in candidates using the given
    find_library() function (or ctypes.util.find_library).
    Returns the first library found, which can be the library's name
    or the path to the library file, depending on find_library().
    Returns None if no library is found.

    arguments:
    * candidates   -- iterable with library names
    * find_library -- function that takes one positional arg (candidate)
                      and returns a non-empty str if a library has been found.
                      Any "false" value (None,False,empty str) is interpreted
                      as "library not found".
                      Defaults to ctypes.util.find_library if not given or
                      None.
    """
    if find_library is None:
        find_library = ctypes.util.find_library

    use_dll_workaround = (
        sys.platform == 'win32' and find_library is ctypes.util.find_library
    )

    for candidate in candidates:
        # Workaround for CPython 3.3 issue#16283 / pyusb #14
        if use_dll_workaround:
            candidate += '.dll'

        libname = find_library(candidate)
        if libname:
            return libname
    # -- end for
    return None
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def user(pid):
  """
  Provides the user a process is running under.

  :param int pid: process id of the process to be queried

  :returns: **str** with the username a process is running under, **None** if
    it can't be determined
  """

  if not isinstance(pid, int) or pid < 0:
    return None

  if stem.util.proc.is_available():
    try:
      import pwd  # only available on unix platforms

      uid = stem.util.proc.uid(pid)

      if uid and uid.isdigit():
        return pwd.getpwuid(int(uid)).pw_name
    except:
      pass

  if is_available('ps'):
    results = call('ps -o user %s' % pid, [])

    if len(results) >= 2:
      return results[1].strip()

  return None
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def start_time(pid):
  """
  Provides the unix timestamp when the given process started.

  :param int pid: process id of the process to be queried

  :returns: **float** for the unix timestamp when the process began, **None**
    if it can't be determined
  """

  if not isinstance(pid, int) or pid < 0:
    return None

  if stem.util.proc.is_available():
    try:
      return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])
    except IOError:
      pass

  try:
    ps_results = call('ps -p %s -o etime' % pid, [])

    if len(ps_results) >= 2:
      etime = ps_results[1].strip()
      return time.time() - stem.util.str_tools.parse_short_time_label(etime)
  except:
    pass

  return None
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def set_process_name(process_name):
  """
  Renames our current process from "python <args>" to a custom name. This is
  best-effort, not necessarily working on all platforms.

  **Note:** This might have issues on FreeBSD (:trac:`9804`).

  :param str process_name: new name for our process
  """

  # This is mostly based on...
  #
  # http://www.rhinocerus.net/forum/lang-python/569677-setting-program-name-like-0-perl.html#post2272369
  #
  # ... and an adaptation by Jake...
  #
  # https://github.com/ioerror/chameleon
  #
  # A cleaner implementation is available at...
  #
  # https://github.com/cream/libs/blob/b38970e2a6f6d2620724c828808235be0445b799/cream/util/procname.py
  #
  # but I'm not quite clear on their implementation, and it only does targeted
  # argument replacement (ie, replace argv[0], argv[1], etc but with a string
  # the same size).

  _set_argv(process_name)

  if platform.system() == 'Linux':
    _set_prctl_name(process_name)
  elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):
    _set_proc_title(process_name)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def _set_prctl_name(process_name):
  """
  Sets the prctl name, which is used by top and killall. This appears to be
  Linux specific and has the max of 15 characters.

  This is from...
  http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/923034#923034
  """

  libc = ctypes.CDLL(ctypes.util.find_library('c'))
  name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
  name_buffer.value = stem.util.str_tools._to_bytes(process_name)
  libc.prctl(PR_SET_NAME, ctypes.byref(name_buffer), 0, 0, 0)
项目:mouse    作者:boppreh    | 项目源码 | 文件源码
def build_display():
    global display, window, x11
    if display and window and x11: return
    x11 = ctypes.cdll.LoadLibrary(ctypes.util.find_library('X11'))
    # Required because we will have multiple threads calling x11,
    # such as the listener thread and then main using "move_to".
    x11.XInitThreads()
    display = x11.XOpenDisplay(None)
    # Known to cause segfault in Fedora 23 64bits, no known workarounds.
    # http://stackoverflow.com/questions/35137007/get-mouse-position-on-linux-pure-python
    window = x11.XDefaultRootWindow(display)
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def openLibrary():
    global ssl
    try:
        if sys.platform.startswith("win"):
            dll_path = "src/lib/opensslVerify/libeay32.dll"
        elif sys.platform == "cygwin":
            dll_path = "/bin/cygcrypto-1.0.0.dll"
        else:
            dll_path = "/usr/local/ssl/lib/libcrypto.so"
        ssl = _OpenSSL(dll_path)
        assert ssl
    except Exception, err:
        ssl = _OpenSSL(ctypes.util.find_library('ssl') or ctypes.util.find_library('crypto') or ctypes.util.find_library('libcrypto') or 'libeay32')
项目:zeronet-debian    作者:bashrc    | 项目源码 | 文件源码
def disableSSLCompression():
    import ctypes
    import ctypes.util
    try:
        openssl = openLibrary()
        openssl.SSL_COMP_get_compression_methods.restype = ctypes.c_void_p
    except Exception, err:
        logging.debug("Disable SSL compression failed: %s (normal on Windows)" % err)
        return False

    openssl.sk_zero.argtypes = [ctypes.c_void_p]
    openssl.sk_zero(openssl.SSL_COMP_get_compression_methods())
    logging.debug("Disabled SSL compression on %s" % openssl)
项目:iotronic-lightning-rod    作者:openstack    | 项目源码 | 文件源码
def __init__(self, board, session):
        super(VfsManager, self).__init__("VFS", board)

        self.session = session
        self.board = board

        """
        #print session
        from iotronic_lightningrod.modules import vfs_library
        fuse=vfs_library.FuseLib("/opt/AAA")
        print fuse.getattr("/aaa.txt")
        """

        libcPath = ctypes.util.find_library("c")
        self.libc = ctypes.CDLL(libcPath)
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def user(pid):
  """
  Provides the user a process is running under.

  :param int pid: process id of the process to be queried

  :returns: **str** with the username a process is running under, **None** if
    it can't be determined
  """

  if not isinstance(pid, int) or pid < 0:
    return None

  if stem.util.proc.is_available():
    try:
      import pwd  # only available on unix platforms

      uid = stem.util.proc.uid(pid)

      if uid and uid.isdigit():
        return pwd.getpwuid(int(uid)).pw_name
    except:
      pass

  if is_available('ps'):
    results = call('ps -o user %s' % pid, [])

    if len(results) >= 2:
      return results[1].strip()

  return None
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def start_time(pid):
  """
  Provides the unix timestamp when the given process started.

  :param int pid: process id of the process to be queried

  :returns: **float** for the unix timestamp when the process began, **None**
    if it can't be determined
  """

  if not isinstance(pid, int) or pid < 0:
    return None

  if stem.util.proc.is_available():
    try:
      return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])
    except IOError:
      pass

  try:
    ps_results = call('ps -p %s -o etime' % pid, [])

    if len(ps_results) >= 2:
      etime = ps_results[1].strip()
      return time.time() - stem.util.str_tools.parse_short_time_label(etime)
  except:
    pass

  return None
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def set_process_name(process_name):
  """
  Renames our current process from "python <args>" to a custom name. This is
  best-effort, not necessarily working on all platforms.

  **Note:** This might have issues on FreeBSD (:trac:`9804`).

  :param str process_name: new name for our process
  """

  # This is mostly based on...
  #
  # http://www.rhinocerus.net/forum/lang-python/569677-setting-program-name-like-0-perl.html#post2272369
  #
  # ... and an adaptation by Jake...
  #
  # https://github.com/ioerror/chameleon
  #
  # A cleaner implementation is available at...
  #
  # https://github.com/cream/libs/blob/b38970e2a6f6d2620724c828808235be0445b799/cream/util/procname.py
  #
  # but I'm not quite clear on their implementation, and it only does targeted
  # argument replacement (ie, replace argv[0], argv[1], etc but with a string
  # the same size).

  _set_argv(process_name)

  if platform.system() == 'Linux':
    _set_prctl_name(process_name)
  elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):
    _set_proc_title(process_name)
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def _set_prctl_name(process_name):
  """
  Sets the prctl name, which is used by top and killall. This appears to be
  Linux specific and has the max of 15 characters.

  This is from...
  http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/923034#923034
  """

  libc = ctypes.CDLL(ctypes.util.find_library('c'))
  name_buffer = ctypes.create_string_buffer(len(process_name) + 1)
  name_buffer.value = stem.util.str_tools._to_bytes(process_name)
  libc.prctl(PR_SET_NAME, ctypes.byref(name_buffer), 0, 0, 0)
项目:python-doublescript    作者:fdintino    | 项目源码 | 文件源码
def mprotect_libc(addr, size, flags):
    libc = ctypes.CDLL(ctypes.util.find_library('libc'), use_errno=True)
    libc.mprotect.argtypes = [c_void_p, c_size_t, c_int]
    libc.mprotect.restype = c_int
    addr_align = addr & ~(PAGE_SIZE - 1)
    mem_end = (addr + size) & ~(PAGE_SIZE - 1)
    if (addr + size) > mem_end:
        mem_end += PAGE_SIZE
    memlen = mem_end - addr_align
    ret = libc.mprotect(addr_align, memlen, flags)
    if ret == -1:
        e = ctypes.get_errno()
        raise OSError(e, errno.errorcodes[e], os.strerror(e))
项目:nfcpy    作者:nfcpy    | 项目源码 | 文件源码
def __init__(self, stream=None):
        super(WindowsColorStreamHandler, self).__init__(stream)
        # get file handle for the stream
        import ctypes, ctypes.util
        crtname = ctypes.util.find_msvcrt()
        crtlib = ctypes.cdll.LoadLibrary(crtname)
        self._outhdl = crtlib._get_osfhandle(self.stream.fileno())
项目:bitencrypt    作者:OriginalMy    | 项目源码 | 文件源码
def loadOpenSSL():
    global OpenSSL
    from os import path, environ
    from ctypes.util import find_library

    libdir = []
    if getattr(sys,'frozen', None):
        if 'darwin' in sys.platform:
            libdir.extend([
                path.join(environ['RESOURCEPATH'], '..', 'Frameworks','libcrypto.dylib'),
                path.join(environ['RESOURCEPATH'], '..', 'Frameworks','libcrypto.1.0.0.dylib')
                ])
        elif 'win32' in sys.platform or 'win64' in sys.platform:
            libdir.append(path.join(sys._MEIPASS, 'libeay32.dll'))
        else:
            libdir.extend([
                path.join(sys._MEIPASS, 'libcrypto.so'),
                path.join(sys._MEIPASS, 'libssl.so'),
                path.join(sys._MEIPASS, 'libcrypto.so.1.0.0'),
                path.join(sys._MEIPASS, 'libssl.so.1.0.0'),
            ])
    if 'darwin' in sys.platform:
        libdir.extend(['libcrypto.dylib', '/usr/local/opt/openssl/lib/libcrypto.dylib'])
    elif 'win32' in sys.platform or 'win64' in sys.platform:
        libdir.append('libeay32.dll')
    else:
        libdir.append('libcrypto.so')
        libdir.append('libssl.so')
    if 'linux' in sys.platform or 'darwin' in sys.platform or 'freebsd' in sys.platform:
        libdir.append(find_library('ssl'))
    elif 'win32' in sys.platform or 'win64' in sys.platform:
        libdir.append(find_library('libeay32'))
    for library in libdir:
        try:
            OpenSSL = _OpenSSL(library)
            return
        except:
            pass
    raise Exception("Couldn't find and load the OpenSSL library. You must install it.")
项目:pysciter    作者:sciter-sdk    | 项目源码 | 文件源码
def _init_lib():
        if hasattr(_init_lib, '_dll'):
            return _init_lib._dll

        import ctypes.util
        lib = ctypes.cdll.LoadLibrary(ctypes.util.find_library('gtk-3'))
        _init_lib._dll = lib

        lib.gtk_widget_get_toplevel.restype = LPCVOID
        lib.gtk_widget_get_toplevel.argtypes = [LPCVOID]

        lib.gtk_init.argtypes = [LPCVOID, LPCVOID]
        lib.gtk_widget_get_toplevel.argtypes = [LPCVOID]
        lib.gtk_widget_hide.argtypes = [LPCVOID]
        lib.gtk_window_iconify.argtypes = [LPCVOID]
        lib.gtk_window_maximize.argtypes = [LPCVOID]
        lib.gtk_window_present.argtypes = [LPCVOID]
        lib.gtk_window_close.argtypes = [LPCVOID]
        lib.gtk_window_get_title.argtypes = [LPCVOID]
        lib.gtk_window_set_title.argtypes = [LPCVOID, LPCSTR]
        lib.gtk_main.argtypes = []
        lib.gtk_main_quit.argtypes = []

        lib.gtk_init(None, None)
        return lib

    #
项目:ClassiPi    作者:mugroma3    | 项目源码 | 文件源码
def init(self):
        assert ctypes

        try_libc_name = 'c'
        if sys.platform.startswith('freebsd'):
            try_libc_name = 'inotify'

        libc_name = None
        try:
            libc_name = ctypes.util.find_library(try_libc_name)
        except (OSError, IOError):
            pass  # Will attemp to load it with None anyway.

        self._libc = ctypes.CDLL(libc_name, use_errno=True)
        self._get_errno_func = ctypes.get_errno

        # Eventually check that libc has needed inotify bindings.
        if (not hasattr(self._libc, 'inotify_init') or
            not hasattr(self._libc, 'inotify_add_watch') or
            not hasattr(self._libc, 'inotify_rm_watch')):
            return False

        self._libc.inotify_init.argtypes = []
        self._libc.inotify_init.restype = ctypes.c_int
        self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p,
                                                 ctypes.c_uint32]
        self._libc.inotify_add_watch.restype = ctypes.c_int
        self._libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
        self._libc.inotify_rm_watch.restype = ctypes.c_int
        return True
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def init(self):
        assert ctypes

        try_libc_name = 'c'
        if sys.platform.startswith('freebsd'):
            try_libc_name = 'inotify'

        libc_name = None
        try:
            libc_name = ctypes.util.find_library(try_libc_name)
        except (OSError, IOError):
            pass  # Will attemp to load it with None anyway.

        self._libc = ctypes.CDLL(libc_name, use_errno=True)
        self._get_errno_func = ctypes.get_errno

        # Eventually check that libc has needed inotify bindings.
        if (not hasattr(self._libc, 'inotify_init') or
            not hasattr(self._libc, 'inotify_add_watch') or
            not hasattr(self._libc, 'inotify_rm_watch')):
            return False

        self._libc.inotify_init.argtypes = []
        self._libc.inotify_init.restype = ctypes.c_int
        self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p,
                                                 ctypes.c_uint32]
        self._libc.inotify_add_watch.restype = ctypes.c_int
        self._libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
        self._libc.inotify_rm_watch.restype = ctypes.c_int
        return True
项目:driveboardapp    作者:nortd    | 项目源码 | 文件源码
def test_ctypes_CDLL_c(pyi_builder):
    # Make sure we are able to load the MSVCRXX.DLL resp. libc.so we are
    # currently bound. This is some of a no-brainer since the resp. dll/so
    # is collected anyway.
    pyi_builder.test_source(
        """
        import ctypes, ctypes.util
        lib = ctypes.CDLL(ctypes.util.find_library('c'))
        assert lib is not None
        """)
项目:eos-data-distribution    作者:endlessm    | 项目源码 | 文件源码
def _fallocate():
    libc_name = ctypes.util.find_library('c')
    libc = ctypes.CDLL(libc_name)

    raw_fallocate = libc.fallocate
    raw_fallocate.restype = ctypes.c_int
    raw_fallocate.argtypes = [
        ctypes.c_int, ctypes.c_int, ctypes.c_int64, ctypes.c_int64]

    def fallocate(fd, offs, size, mode=FALLOC_FL_KEEP_SIZE):
        ret = raw_fallocate(fd, mode, offs, size)
        if ret != 0:
            raise IOError(ctypes.get_errno())

    return fallocate
项目:disco    作者:b1naryth1ef    | 项目源码 | 文件源码
def find_library():
        if sys.platform == 'win32':
            raise Exception('Cannot auto-load opus on Windows, please specify full library path')

        return ctypes.util.find_library('opus')
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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
项目:dymo-m10-python    作者:pbrf    | 项目源码 | 文件源码
def locate_library (candidates, find_library=ctypes.util.find_library):
    """Tries to locate a library listed in candidates using the given
    find_library() function (or ctypes.util.find_library).
    Returns the first library found, which can be the library's name
    or the path to the library file, depending on find_library().
    Returns None if no library is found.

    arguments:
    * candidates   -- iterable with library names
    * find_library -- function that takes one positional arg (candidate)
                      and returns a non-empty str if a library has been found.
                      Any "false" value (None,False,empty str) is interpreted
                      as "library not found".
                      Defaults to ctypes.util.find_library if not given or
                      None.
    """
    if find_library is None:
        find_library = ctypes.util.find_library

    use_dll_workaround = (
        sys.platform == 'win32' and find_library is ctypes.util.find_library
    )

    for candidate in candidates:
        # Workaround for CPython 3.3 issue#16283 / pyusb #14
        if use_dll_workaround:
            candidate += '.dll'

        libname = find_library(candidate)
        if libname:
            return libname
    # -- end for
    return None
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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
项目:sktacc    作者:jclee81    | 项目源码 | 文件源码
def __init__(self, stream=None):
        logging.StreamHandler.__init__(self, stream)
        # get file handle for the stream
        import 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())
项目:gitsome    作者:donnemartin    | 项目源码 | 文件源码
def setup_readline():
    """Sets up the readline module and completion supression, if available."""
    global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE
    if RL_COMPLETION_SUPPRESS_APPEND is not None:
        return
    try:
        import readline
    except ImportError:
        return
    import ctypes
    import ctypes.util
    readline.set_completer_delims(' \t\n')
    if not readline.__file__.endswith('.py'):
        RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__)
        try:
            RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll(
                lib, 'rl_completion_suppress_append')
        except ValueError:
            # not all versions of readline have this symbol, ie Macs sometimes
            RL_COMPLETION_SUPPRESS_APPEND = None
        RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size')
    env = builtins.__xonsh_env__
    # reads in history
    readline.set_history_length(-1)
    ReadlineHistoryAdder()
    # sets up IPython-like history matching with up and down
    readline.parse_and_bind('"\e[B": history-search-forward')
    readline.parse_and_bind('"\e[A": history-search-backward')
    # Setup Shift-Tab to indent
    readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT')))

    # handle tab completion differences found in libedit readline compatibility
    # as discussed at http://stackoverflow.com/a/7116997
    if readline.__doc__ and 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")