def python(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) dll.InitializePython.restype = BOOL dll.InitializePython.argtypes = [HMODULE, PVOID, PDWORD] return dll
def load_module(name, verbose=True): if verbose: print('Loading module', name) try: if get_os_name() == 'osx': mode = ctypes.RTLD_LOCAL else: mode = ctypes.RTLD_GLOBAL if '.so' in name: ctypes.PyDLL(name, mode=mode) else: ctypes.PyDLL(os.path.join(get_repo_directory(), 'build', get_dll_name(name)), mode=mode) except Exception as e: print(Fore.YELLOW + "Warning: module [{}] loading failed: {}".format(name, e) + Style.RESET_ALL)
def _get_cdll(): global _CDLL if not _CDLL: # NOTE(ralonsoh): from https://docs.python.org/3.6/library/ # ctypes.html#ctypes.PyDLL: "Instances of this class behave like CDLL # instances, except that the Python GIL is not released during the # function call, and after the function execution the Python error # flag is checked." # Check https://bugs.launchpad.net/neutron/+bug/1870352 _CDLL = ctypes.PyDLL(ctypes_util.find_library('c'), use_errno=True) return _CDLL
def rtl(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) dll.InitializeRtl.restype = BOOL dll.InitializeRtl.argtypes = [ PRTL, PULONG, ] return dll
def get_dll(version): """returns a PyDLL for a specific python version""" if version == 2: for name in (OLD_PY2_FRAMEWORK, NEW_PY2_FRAMEWORK): path = os.path.join(EXE_DIR, "Frameworks", name + ".framework", name) if os.path.exists(path): return ctypes.PyDLL(path) raise RuntimeError("Could not load any Python 2 Framework!") elif version == 3: return ctypes.pythonapi else: raise ValueError("Unknown Python version: '{v}'!".format(v=version))
def profile(file, globals_obj, locals_obj, profdll): global profiler, pyprofdll pyprofdll = ctypes.PyDLL(profdll) profiler = pyprofdll.CreateProfiler(sys.dllhandle) handle = start_profiling() try: execfile(file, globals_obj, locals_obj) finally: pyprofdll.CloseThread(handle) pyprofdll.CloseProfiler(profiler)
def apply_dl_hacks(): if have_ctypes_dlopen: setattr(ctypes, '_system_dlopen', ctypes._dlopen) if have_ctypes_util: ctypes.util._system_find_library = ctypes.util.find_library if hasattr(ctypes.util, '_findLib_gcc'): ctypes.util._findLib_gcc = lambda name: None else: ctypes_util = pupy.make_module('ctypes.util') setattr(ctypes_util, '_system_find_library', _find_library) ctypes._dlopen = _pupy_dlopen ctypes.util.find_library = _pupy_find_library libpython = None if sys.platform == 'win32': try: libpython = ctypes.PyDLL('python27.dll') except WindowsError: pupy.dprint('python27.dll not found') else: for libname in (None, 'libpython2.7.so.1.0', 'libpython2.7.so'): try: candidate = ctypes.PyDLL(libname) except OSError: continue if hasattr(candidate, '_Py_PackageContext'): libpython = candidate break if libpython is not None: pupy.dprint('Set ctypes.pythonapi to {}', libpython) ctypes.pythonapi = libpython
def config(): if sys.platform.startswith("win"): return libdl = ctypes.CDLL(ctypes.util.find_library('dl')) libc = ctypes.PyDLL(None) class Dl_info(ctypes.Structure): _fields_ = (('dli_fname', ctypes.c_char_p), ('dli_fbase', ctypes.c_void_p), ('dli_sname', ctypes.c_char_p), ('dli_saddr', ctypes.c_void_p)) libdl.dladdr.argtypes = (ctypes.c_void_p, ctypes.POINTER(Dl_info)) info = Dl_info() libdl.dladdr(libc.Py_IsInitialized, ctypes.byref(info)) python = sys.executable libpython = info.dli_fname.decode() try: lib = ctypes.PyDLL(libpython) except OSError: libpython = "" else: if lib.Py_IsInitialized() == 0: libpython = "" try: import sysconfig pythonhome = sysconfig.get_config_vars('prefix')[0] + ":" + \ sysconfig.get_config_vars('exec_prefix')[0] except Exception: pythonhome = None numpy = module_exists("numpy") return (python, libpython, pythonhome, numpy)
def __init__(self, libjulia_path, bindir, sysimage): self.libjulia_path = libjulia_path self.bindir = bindir self.sysimage = sysimage if not os.path.exists(libjulia_path): raise RuntimeError("Julia library (\"libjulia\") not found! {}".format(libjulia_path)) # fixes a specific issue with python 2.7.13 # ctypes.windll.LoadLibrary refuses unicode argument # http://bugs.python.org/issue29294 if sys.version_info >= (2, 7, 13) and sys.version_info < (2, 7, 14): libjulia_path = libjulia_path.encode("ascii") self.libjulia = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL) setup_libjulia(self.libjulia)
def join_all_spaces(qtwin): """Create a full-screen button on qtwin. The window needs to be already shown. """ view = qtwin.effectiveWinId() print(view) print(dir(view)) print(view.ascobject()) cocoawin = send1(PyCObject_AsVoidPtr(view.ascobject()), window_sel) import ctypes, objc _objc = ctypes.PyDLL(objc._objc.__file__) _objc.PyObjCObject_New.restype = ctypes.py_object _objc.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] def objc_object(id): return _objc.PyObjCObject_New(id, 0, 1) objc_object(cocoawin).setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenAuxiliary | NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary)
def vspyprof(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) dll.CreateProfiler.restype = c_void_p dll.CreateCustomProfiler.restype = c_void_p dll.CreateCustomProfiler.argtypes = [c_void_p, ctypes.c_void_p] dll.CloseThread.argtypes = [c_void_p] dll.CloseProfiler.argtypes = [c_void_p] dll.InitProfiler.argtypes = [c_void_p] dll.InitProfiler.restype = c_void_p #dll.SetTracing.argtypes = [c_void_p] #dll.UnsetTracing.argtypes = [c_void_p] #dll.IsTracing.argtypes = [c_void_p] #dll.IsTracing.restype = c_bool return dll
def load_module(library_name, *args): ''' Load a module from a library and one or more module names. Args: *args: Module names. ''' try: modules = [] module_library = ctypes.PyDLL(library_name + "." + ext) for module_name in args: module = getattr(module_library, 'PyInit_' + module_name) module.restype = ctypes.py_object modules.append( module() ) if len(modules) == 1: return modules[0] else: return tuple(modules) except: return None
def tracer(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) dll.InitializeTraceStores.restype = BOOL dll.InitializeTraceStores.argtypes = [ PRTL, PWSTR, PVOID, PDWORD, PDWORD, ] dll.InitializeTraceContext.restype = BOOL dll.InitializeTraceContext.argtypes = [ PRTL, PTRACE_CONTEXT, PDWORD, PTRACE_SESSION, PTRACE_STORES, PVOID, ] dll.InitializeTraceSession.restype = BOOL dll.InitializeTraceSession.argtypes = [ PRTL, PTRACE_SESSION, PDWORD ] dll.SubmitTraceStoreFileExtensionThreadpoolWork.restype = None dll.SubmitTraceStoreFileExtensionThreadpoolWork.argtypes = [ PTRACE_STORE, ] #dll.CallSystemTimer.restype = BOOL #dll.CallSystemTimer.argtypes = [ # PFILETIME, # PVOID, #] return dll
def pythontracer(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) dll.InitializePythonTraceContext.restype = BOOL dll.InitializePythonTraceContext.argtypes = [ PPYTHON_TRACE_CONTEXT, PULONG, PPYTHON, PTRACE_CONTEXT, PPYTRACEFUNC, PUSERDATA ] dll.StartTracing.restype = BOOL dll.StartTracing.argtypes = [ PPYTHON_TRACE_CONTEXT, ] dll.StopTracing.restype = BOOL dll.StopTracing.argtypes = [ PPYTHON_TRACE_CONTEXT, ] return dll
def load_libjulia(self, config): if self._libjulia_loaded: return jlinfo = config.juliainfo() BINDIR, libjulia_path, image_file = jlinfo[:3] logger.debug("Base.Sys.BINDIR = %s", BINDIR) logger.debug("libjulia_path = %s", libjulia_path) if not os.path.exists(libjulia_path): raise RuntimeError( 'Julia library ("libjulia") not found! {}'.format( libjulia_path)) self.julia_bindir = BINDIR.encode("utf-8") self.image_file = image_file # fixes a specific issue with python 2.7.13 # ctypes.windll.LoadLibrary refuses unicode argument # http://bugs.python.org/issue29294 if (2, 7, 13) <= sys.version_info < (2, 7, 14): libjulia_path = libjulia_path.encode("ascii") libjulia = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL) try: jl_init_with_image = libjulia.jl_init_with_image except AttributeError: try: jl_init_with_image = libjulia.jl_init_with_image__threading except AttributeError: raise RuntimeError( "No libjulia entrypoint found! (tried jl_init_with_image" " and jl_init_with_image__threading)") jl_init_with_image.argtypes = [c_char_p, c_char_p] self.jl_init_with_image = jl_init_with_image self._libjulia = libjulia self._libjulia_loaded = True
def ctypes_open(lib_name): import os import sys if sys.platform.startswith('darwin'): exts = ['.dylib', '.so'] elif sys.platform.startswith('linux'): exts = ['.so'] else: # Windows exts = ['.pyd', '.dll'] os.environ['PATH'] = os.environ['PATH'] \ + ';' + os.path.join(os.path.dirname(__file__), 'lib') for ext in exts: if os.path.isabs(lib_name): lib_path = lib_name else: lib_path = os.path.join(os.path.dirname(__file__), lib_name) lib_path += ext if not os.path.exists(lib_path): continue lib = ctypes.PyDLL(lib_path) break else: raise RuntimeError("Unable to find '%s' shared library" % lib_name) return lib
def __init__(self): moddir = os.path.dirname(os.path.abspath(__file__)) # self._lib = ctypes.cdll.LoadLibrary('%s/libAks.so' % moddir) self._lib = ctypes.PyDLL('%s/libAks.so' % moddir) # AKS::SysManager* createSysManager(); self._lib.createSysManagerExt.restype = ctypes.c_void_p self._lib.createSysManagerExt.argtypes = [] # void loadKernel(AKS::SysManager* sysMan, const char* kernelDir); self._lib.loadKernels.argtypes = [ctypes.c_void_p, ctypes.c_char_p] # void loadGraphs(AKS::SysManager* sysMan, const char* graphPath); self._lib.loadGraphs.argtypes = [ctypes.c_void_p, ctypes.c_char_p] # AKS::AIGraph* getGraph(AKS::SysManager* sysMan, const char* graphName); self._lib.getGraph.restype = ctypes.c_void_p self._lib.getGraph.argtypes = [ctypes.c_void_p, ctypes.c_char_p] # void enqueueJob(AKS::SysManager* sysMan, AKS::AIGraph* graph, # const char* imagePath, AKS::NodeParams* params); self._lib.enqueueJob.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p] # void waitForAllResults(AKS::SysManager* sysMan); self._lib.waitForAllResults.argtypes = [ctypes.c_void_p, ctypes.c_void_p] # void resetTimer(AKS::SysManager* sysMan); self._lib.resetTimer.argtypes = [ctypes.c_void_p] # void report(AKS::SysManager* sysMan, AKS::AIGraph* graph); self._lib.report.argtypes = [ctypes.c_void_p, ctypes.c_void_p] # void deleteSysManager(AKS::SysManager* sysMan); self._lib.deleteSysManagerExt.argtypes = [] self._csysmgr = self._lib.createSysManagerExt()
# Minimal repl.c to support precompilation with python symbols already loaded import ctypes import sys import os from ctypes import * if sys.platform.startswith('darwin'): sh_ext = ".dylib" elif sys.platform.startswith('win32'): sh_ext = ".dll" else: sh_ext = ".so" libjulia_path = os.environ["PYCALL_LIBJULIA_PATH"] + "/lib" + os.environ[ "PYCALL_JULIA_FLAVOR"] + sh_ext libjulia = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL) os.environ["JULIA_HOME"] = os.environ[ "PYCALL_JULIA_HOME"] # TODO: this can be removed when dropping Julia v0.6 os.environ["JULIA_BINDIR"] = os.environ["PYCALL_JULIA_HOME"] if not hasattr(libjulia, "jl_init_with_image"): if hasattr(libjulia, "jl_init_with_image__threading"): libjulia.jl_init_with_image = libjulia.jl_init_with_image__threading else: raise ImportError( "No libjulia entrypoint found! (tried jl_init and jl_init__threading)" ) # Set up the calls from libjulia we'll use libjulia.jl_parse_opts.argtypes = [POINTER(c_int), POINTER(POINTER(c_char_p))] libjulia.jl_parse_opts.restype = None libjulia.jl_init_with_image.argtypes = [c_char_p, c_char_p] libjulia.jl_init_with_image.restype = None
# https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 """This module contains function declarations for several functions of libc (based on ctypes) and constants relevant for these functions. """ import ctypes as _ctypes from ctypes import c_int, c_uint32, c_long, c_ulong, c_size_t, c_char_p, c_void_p import os as _os _libc = _ctypes.CDLL("libc.so.6", use_errno=True) """Reference to standard C library.""" _libc_with_gil = _ctypes.PyDLL("libc.so.6", use_errno=True) """Reference to standard C library, and we hold the GIL during all function calls.""" def _check_errno(result, func, arguments): assert func.restype in [c_int, c_void_p] if (func.restype == c_int and result == -1) or (func.restype == c_void_p and c_void_p(result).value == c_void_p(-1).value): errno = _ctypes.get_errno() try: func_name = func.__name__ except AttributeError: func_name = "__unknown__" msg = (func_name + "(" + ", ".join(map(str, arguments)) + ") failed: " + _os.strerror(errno))
def __init__(self, init_julia=True, jl_runtime_path=None, jl_init_path=None, debug=False): """Create a Python object that represents a live Julia interpreter. Parameters ========== init_julia : bool If True, try to initialize the Julia interpreter. If this code is being called from inside an already running Julia, the flag should be passed as False so the interpreter isn't re-initialized. jl_runtime_path : str (optional) Path to your Julia binary, e.g. "/usr/local/bin/julia" jl_init_path : str (optional) Path to give to jl_init relative to which we find sys.so, (defaults to jl_runtime_path or NULL) debug : bool If True, print some debugging information to STDERR Note that it is safe to call this class constructor twice in the same process with `init_julia` set to True, as a global reference is kept to avoid re-initializing it. The purpose of the flag is only to manage situations when Julia was initialized from outside this code. """ self.is_debugging = debug # Ugly hack to register the julia interpreter globally so we can reload # this extension without trying to re-open the shared lib, which kills # the python interpreter. Nasty but useful while debugging if _julia_runtime[0]: self.api = _julia_runtime[0] return self._debug() # so that debug message is shown nicely w/ pytest if init_julia: if jl_runtime_path: runtime = jl_runtime_path else: runtime = 'julia' JULIA_HOME, libjulia_path, image_file, depsjlexe = juliainfo( runtime) self._debug("pyprogramname =", depsjlexe) self._debug("sys.executable =", sys.executable) exe_differs = is_different_exe(depsjlexe, sys.executable) self._debug("exe_differs =", exe_differs) self._debug("JULIA_HOME = %s, libjulia_path = %s" % (JULIA_HOME, libjulia_path)) if not os.path.exists(libjulia_path): raise JuliaError( "Julia library (\"libjulia\") not found! {}".format( libjulia_path)) # fixes a specific issue with python 2.7.13 # ctypes.windll.LoadLibrary refuses unicode argument # http://bugs.python.org/issue29294 if sys.version_info >= (2, 7, 13) and sys.version_info < (2, 7, 14): libjulia_path = libjulia_path.encode("ascii") self.api = ctypes.PyDLL(libjulia_path, ctypes.RTLD_GLOBAL) if not jl_init_path: if jl_runtime_path: jl_init_path = os.path.dirname( os.path.realpath(jl_runtime_path)).encode("utf-8") else: jl_init_path = JULIA_HOME.encode( "utf-8") # initialize with JULIA_HOME use_separate_cache = exe_differs or determine_if_statically_linked( ) if use_separate_cache: PYCALL_JULIA_HOME = os.path.join( os.path.dirname(os.path.realpath(__file__)), "fake-julia").replace("\\", "\\\\") os.environ[ "JULIA_HOME"] = PYCALL_JULIA_HOME # TODO: this line can be removed when dropping Julia v0.6 os.environ["JULIA_BINDIR"] = PYCALL_JULIA_HOME jl_init_path = PYCALL_JULIA_HOME.encode("utf-8") if not hasattr(self.api, "jl_init_with_image"): if hasattr(self.api, "jl_init_with_image__threading"): self.api.jl_init_with_image = self.api.jl_init_with_image__threading else: raise ImportError( "No libjulia entrypoint found! (tried jl_init_with_image and jl_init_with_image__threading)" ) self.api.jl_init_with_image.argtypes = [char_p, char_p] self._debug("calling jl_init_with_image(%s, %s)" % (jl_init_path, image_file)) self.api.jl_init_with_image(jl_init_path, image_file.encode("utf-8")) self._debug("seems to work...") else: # we're assuming here we're fully inside a running Julia process, # so we're fishing for symbols in our own process table self.api = ctypes.PyDLL('') # Store the running interpreter reference so we can start using it via self.call self.api.jl_.argtypes = [void_p] self.api.jl_.restype = None # Set the return types of some of the bridge functions in ctypes terminology self.api.jl_eval_string.argtypes = [char_p] self.api.jl_eval_string.restype = void_p self.api.jl_exception_occurred.restype = void_p self.api.jl_typeof_str.argtypes = [void_p] self.api.jl_typeof_str.restype = char_p self.api.jl_call2.argtypes = [void_p, void_p, void_p] self.api.jl_call2.restype = void_p self.api.jl_get_field.argtypes = [void_p, char_p] self.api.jl_get_field.restype = void_p self.api.jl_typename_str.restype = char_p self.api.jl_unbox_voidpointer.argtypes = [void_p] self.api.jl_unbox_voidpointer.restype = py_object self.api.jl_exception_clear.restype = None self.api.jl_stderr_obj.argtypes = [] self.api.jl_stderr_obj.restype = void_p self.api.jl_stderr_stream.argtypes = [] self.api.jl_stderr_stream.restype = void_p self.api.jl_printf.restype = ctypes.c_int self.api.jl_exception_clear() if init_julia: if use_separate_cache: # First check that this is supported self._call(""" if VERSION < v"0.5-" error(\"""Using pyjulia with a statically-compiled version of python or with a version of python that differs from that used by PyCall.jl is not supported on julia 0.4""\") end """) # Intercept precompilation os.environ["PYCALL_PYTHON_EXE"] = sys.executable os.environ["PYCALL_JULIA_HOME"] = PYCALL_JULIA_HOME os.environ["PYJULIA_IMAGE_FILE"] = image_file os.environ["PYCALL_LIBJULIA_PATH"] = os.path.dirname( libjulia_path) # Add a private cache directory. PyCall needs a different # configuration and so do any packages that depend on it. self._call( u"unshift!(Base.LOAD_CACHE_PATH, abspath(Pkg.Dir._pkgroot()," + "\"lib\", \"pyjulia%s-v$(VERSION.major).$(VERSION.minor)\"))" % sys.version_info[0]) # If PyCall.ji does not exist, create an empty file to force # recompilation self._call(u""" isdir(Base.LOAD_CACHE_PATH[1]) || mkpath(Base.LOAD_CACHE_PATH[1]) depsfile = joinpath(Base.LOAD_CACHE_PATH[1],"PyCall.ji") isfile(depsfile) || touch(depsfile) """) self._call(u"using PyCall") # Whether we initialized Julia or not, we MUST create at least one # instance of PyObject and the convert function. Since these will be # needed on every call, we hold them in the Julia object itself so # they can survive across reinitializations. self.api.PyObject = self._call("PyCall.PyObject") self.api.convert = self._call("convert") # Flag process-wide that Julia is initialized and store the actual # runtime interpreter, so we can reuse it across calls and module # reloads. _julia_runtime[0] = self.api self.sprint = self.eval('sprint') self.showerror = self.eval('showerror')
import numpy except ImportError: raise Exception('MonetDBLite requires numpy but import of numpy failed') try: import pandas except ImportError: raise Exception('MonetDBLite requires pandas but importing pandas failed') if os.name == 'nt': os.environ["PATH"] += os.pathsep + os.path.dirname( os.path.abspath(__file__)) # make mal_linker happy os.environ["MONETDBLITE_LIBNAME"] = libs[0] dll = ctypes.PyDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)), libs[0]), mode=ctypes.RTLD_GLOBAL) dll.python_monetdblite_init.argtypes = [] dll.python_monetdblite_init.restype = None dll.python_monetdblite_init() dll.python_monetdb_init.argtypes = [ctypes.c_char_p, ctypes.c_int] dll.python_monetdb_init.restype = ctypes.py_object dll.python_monetdb_sql.argtypes = [ctypes.c_void_p, ctypes.c_char_p] dll.python_monetdb_sql.restype = ctypes.py_object dll.python_monetdb_insert.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.py_object ]
# coding: utf-8 import ctypes import cairo # pycairo import cairocffi pycairo = ctypes.PyDLL(cairo._cairo.__file__) pycairo.PycairoContext_FromContext.restype = ctypes.c_void_p pycairo.PycairoContext_FromContext.argtypes = 3 * [ctypes.c_void_p] ctypes.pythonapi.PyList_Append.argtypes = 2 * [ctypes.c_void_p] def _UNSAFE_cairocffi_context_to_pycairo(cairocffi_context): # Sanity check. Continuing with another type would probably segfault. if not isinstance(cairocffi_context, cairocffi.Context): raise TypeError('Expected a cairocffi.Context, got %r' % cairocffi_context) # Create a reference for PycairoContext_FromContext to take ownership of. cairocffi.cairo.cairo_reference(cairocffi_context._pointer) # Casting the pointer to uintptr_t (the integer type as wide as a pointer) # gets the context’s integer address. # On CPython id(cairo.Context) gives the address to the Context type, # as expected by PycairoContext_FromContext. address = pycairo.PycairoContext_FromContext( int(cairocffi.ffi.cast('uintptr_t', cairocffi_context._pointer)), id(cairo.Context), None) assert address # This trick uses Python’s C API # to get a reference to a Python object from its address.
def magic_flush_mro_cache() -> None: ctypes.PyDLL(None).PyType_Modified(ctypes.py_object(object))
def __init__(self, library_path): self._c_lib = ctypes.PyDLL(library_path)
# Copyright (c) Facebook, Inc. and its affiliates. # SPDX-License-Identifier: GPL-3.0-or-later import ctypes import enum from enum import auto import os import _drgn import drgn _drgn_pydll = ctypes.PyDLL(_drgn.__file__) _drgn_cdll = ctypes.CDLL(_drgn.__file__) class _drgn_error(ctypes.Structure): _fields_ = [ ("code", ctypes.c_uint), ("errnum", ctypes.c_int), ("path", ctypes.c_char_p), ("msg", ctypes.c_char_p), ] _drgn_pydll.set_drgn_error.restype = ctypes.c_void_p _drgn_pydll.set_drgn_error.argtypes = [ctypes.POINTER(_drgn_error)] def _check_err(err): if err: _drgn_pydll.set_drgn_error(err)
def sqlite3(path=None, dll=None): assert path or dll if not dll: dll = ctypes.PyDLL(path) return dll
#------------------- # Repository module #------------------- #repository = load_module('lib_simvascular_repository', 'pyRepository') ## Remove the varialbles used here so they don't show up in the doc. del ext del load_module #---------------------------------------------------------- # Python 2.0 #---------------------------------------------------------- else: myDll=ctypes.PyDLL('lib_simvascular_solid.' + ext) myDll.initpySolid() import pySolid as Solid myDll=ctypes.PyDLL('lib_simvascular_polydata_solid.' + ext) myDll.initpySolidPolydata() import pySolidPolydata as SolidPolyData try: myDll=ctypes.PyDLL('lib_simvascular_parasolid_solid.' + ext) myDll.initpySolidParasolid() import pySolidParasolid as SolidParaSolid except: pass myDll=ctypes.PyDLL('lib_simvascular_repository.' + ext) myDll.initpyRepository() import pyRepository as Repository
IN_PYTHONISTA = sys.executable.find('Pythonista') >= 0 if IN_PYTHONISTA: import plistlib _properties = plistlib.readPlist(os.path.join(os.path.dirname(sys.executable), 'Info.plist')) PYTHONISTA_VERSION = _properties['CFBundleShortVersionString'] PYTHONISTA_VERSION_LONG = _properties['CFBundleVersion'] if PYTHONISTA_VERSION < '3.0': python_capi = ctypes.pythonapi else: # The default pythonapi always points to Python 3 in Pythonista 3 # So we need to load the Python 2 API manually python_capi = ctypes.PyDLL( os.path.join(os.path.dirname(sys.executable), 'Frameworks/PythonistaKit.framework/PythonistaKit') ) else: PYTHONISTA_VERSION = '0.0' PYTHONISTA_VERSION_LONG = '000000' python_capi = ctypes.pythonapi platform_string = platform.platform() ON_IPAD = platform_string.find('iPad') >= 0 ON_IOS_8 = platform_string.split('-')[1].startswith('14') M_64 = platform_string.find('64bit') != -1 CTRL_KEY_FLAG = (1 << 18) # Control key for keyCommands CMD_KEY_FLAG = (1 << 20) # Command key
wx.CallAfter(self.StupidMacOSWorkaround) def StupidMacOSWorkaround(self): """ On MacOS for some magical reason opening new frames does not work until you opened a new modal dialog and closed it. If we do this from software, then, as if by magic, the bug which prevents opening extra frames is gone. """ dlg = wx.Dialog(None) wx.PostEvent(dlg, wx.CommandEvent(wx.EVT_CLOSE.typeId)) dlg.ShowModal() dlg.Destroy() if platform.system() == "Darwin": #Mac magic. Dragons live here. THis sets full screen options. try: import ctypes, objc _objc = ctypes.PyDLL(objc._objc.__file__) # PyObject *PyObjCObject_New(id objc_object, int flags, int retain) _objc.PyObjCObject_New.restype = ctypes.py_object _objc.PyObjCObject_New.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int] def setFullScreenCapable(frame): frameobj = _objc.PyObjCObject_New(frame.GetHandle(), 0, 1) NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7 window = frameobj.window() newBehavior = window.collectionBehavior() | NSWindowCollectionBehaviorFullScreenPrimary window.setCollectionBehavior_(newBehavior) except: def setFullScreenCapable(frame): pass
from __future__ import print_function import sys import ctypes import os def trace(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) ctypes.PyDLL("libgnucap.so", mode=ctypes.RTLD_GLOBAL) oldflags = sys.getdlopenflags() if (os.name == "posix"): # python tries to outsmart us, work around that trace("POSIX ON") sys.setdlopenflags(oldflags | ctypes.RTLD_GLOBAL) trace("PYDDL'd") else: untested() from .gnucap_swig import command, parse trace("cmd imported") from .c_comand import CMD, CMD_cmdproc, CMD_command from .c_exp import eval from .component import COMPONENT_ as COMPONENT from .e_base import CKT_BASE_find_wave, CKT_BASE from .e_cardlist import CARD_LIST from .e_elemnt import ELEMENT from .e_node import node_t