diff --git a/appveyor.yml b/appveyor.yml index 85651094..11d057f5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -13,22 +13,32 @@ environment: BATDIR: ci\appveyor\win32 CROSS_VERSION: 1 - # 32 julia latest Python-35 - - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x86/julia-latest-win32.exe" + # 32 julia-1.0 Python-35 + - JULIA_URL: "https://julialang-s3.julialang.org/bin/winnt/x86/1.0/julia-1.0-latest-win32.exe" PYTHONDIR: "C:\\Python35" BATDIR: ci\appveyor\win32 + # 32 julia latest Python-35 + # - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x86/julia-latest-win32.exe" + # PYTHONDIR: "C:\\Python35" + # BATDIR: ci\appveyor\win32 + # 64 julia-0.6 Python-35 - JULIA_URL: "https://julialang-s3.julialang.org/bin/winnt/x64/0.6/julia-0.6-latest-win64.exe" PYTHONDIR: "C:\\Python35-x64" BATDIR: ci\appveyor\win64 CROSS_VERSION: 1 - # 64 julia latest Python-35 - - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x64/julia-latest-win64.exe" + # 64 julia-1.0 Python-35 + - JULIA_URL: "https://julialang-s3.julialang.org/bin/winnt/x64/1.0/julia-1.0-latest-win64.exe" PYTHONDIR: "C:\\Python35-x64" BATDIR: ci\appveyor\win64 + # 64 julia latest Python-35 + # - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x64/julia-latest-win64.exe" + # PYTHONDIR: "C:\\Python35-x64" + # BATDIR: ci\appveyor\win64 + matrix: allow_failures: - JULIA_URL: "https://julialangnightlies-s3.julialang.org/bin/winnt/x86/julia-latest-win32.exe" diff --git a/julia/core.py b/julia/core.py index 95a889e4..48d1d32d 100644 --- a/julia/core.py +++ b/julia/core.py @@ -32,6 +32,8 @@ # this is python 3.3 specific from types import ModuleType, FunctionType +from .find_libpython import find_libpython, normalize_path + #----------------------------------------------------------------------------- # Classes and funtions #----------------------------------------------------------------------------- @@ -42,6 +44,12 @@ def iteritems(d): return iter(d.items()) else: iteritems = dict.iteritems + +# As setting up Julia modifies os.environ, we need to cache it for +# launching subprocesses later in the original environment. +_enviorn = os.environ.copy() + + class JuliaError(Exception): pass @@ -254,7 +262,9 @@ def determine_if_statically_linked(): JuliaInfo = namedtuple( 'JuliaInfo', - ['JULIA_HOME', 'libjulia_path', 'image_file', 'pyprogramname']) + ['JULIA_HOME', 'libjulia_path', 'image_file', + # Variables in PyCall/deps/deps.jl: + 'pyprogramname', 'libpython']) def juliainfo(runtime='julia'): @@ -277,24 +287,61 @@ def juliainfo(runtime='julia'): if PyCall_depsfile !== nothing && isfile(PyCall_depsfile) include(PyCall_depsfile) println(pyprogramname) + println(libpython) end - """]) + """], + # Use the original environment variables to avoid a cryptic + # error "fake-julia/../lib/julia/sys.so: cannot open shared + # object file: No such file or directory": + env=_enviorn) args = output.decode("utf-8").rstrip().split("\n") - if len(args) == 3: - args.append(None) # no pyprogramname set + args.extend([None] * (len(JuliaInfo._fields) - len(args))) return JuliaInfo(*args) def is_same_path(a, b): - a = os.path.normpath(os.path.normcase(a)) - b = os.path.normpath(os.path.normcase(b)) + a = os.path.realpath(os.path.normcase(a)) + b = os.path.realpath(os.path.normcase(b)) return a == b -def is_different_exe(pyprogramname, sys_executable): - if pyprogramname is None: +def is_compatible_exe(jlinfo, _debug=lambda *_: None): + """ + Determine if Python used by PyCall.jl is compatible with this Python. + + Current Python executable is considered compatible if it is dynamically + linked to libpython (usually the case in macOS and Windows) and + both of them are using identical libpython. If this function returns + `True`, PyJulia use the same precompilation cache of PyCall.jl used by + Julia itself. + + Parameters + ---------- + jlinfo : JuliaInfo + A `JuliaInfo` object returned by `juliainfo` function. + """ + _debug("jlinfo.libpython =", jlinfo.libpython) + if jlinfo.libpython is None: + _debug("libpython cannot be read from PyCall/deps/deps.jl") + return False + + if determine_if_statically_linked(): + _debug(sys.executable, "is statically linked.") + return False + + # Note that the following check is OK since statically linked case + # is already excluded. + if is_same_path(jlinfo.pyprogramname, sys.executable): + # In macOS and Windows, find_libpython does not work as good + # as in Linux. We add this shortcut so that PyJulia can work + # in those environments. return True - return not is_same_path(pyprogramname, sys_executable) + + py_libpython = find_libpython() + jl_libpython = normalize_path(jlinfo.libpython) + _debug("py_libpython =", py_libpython) + _debug("jl_libpython =", jl_libpython) + return py_libpython == jl_libpython _julia_runtime = [False] @@ -349,11 +396,10 @@ def __init__(self, init_julia=True, jl_runtime_path=None, jl_init_path=None, runtime = jl_runtime_path else: runtime = 'julia' - JULIA_HOME, libjulia_path, image_file, depsjlexe = juliainfo(runtime) + jlinfo = juliainfo(runtime) + JULIA_HOME, libjulia_path, image_file, depsjlexe = jlinfo[:4] 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)) @@ -371,7 +417,8 @@ def __init__(self, init_julia=True, jl_runtime_path=None, jl_init_path=None, else: jl_init_path = JULIA_HOME.encode("utf-8") # initialize with JULIA_HOME - use_separate_cache = exe_differs or determine_if_statically_linked() + use_separate_cache = not is_compatible_exe(jlinfo, _debug=self._debug) + self._debug("use_separate_cache =", use_separate_cache) if use_separate_cache: PYCALL_JULIA_HOME = os.path.join( os.path.dirname(os.path.realpath(__file__)),"fake-julia").replace("\\","\\\\") @@ -441,16 +488,37 @@ def __init__(self, init_julia=True, jl_runtime_path=None, jl_init_path=None, # 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 + + # If PyCall.jl is already pre-compiled, for the global + # environment, hide it while we are loading PyCall.jl + # for PyJulia which has to compile a new cache if it + # does not exist. However, Julia does not compile a + # new cache if it exists in Base.LOAD_CACHE_PATH[2:end]. + # https://github.com/JuliaPy/pyjulia/issues/92#issuecomment-289303684 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) + for path in Base.LOAD_CACHE_PATH[2:end] + cache = joinpath(path, "PyCall.ji") + backup = joinpath(path, "PyCall.ji.backup") + if isfile(cache) + mv(cache, backup; remove_destination=true) + end + end """) self._call(u"using PyCall") + + if use_separate_cache: + self._call(u""" + for path in Base.LOAD_CACHE_PATH[2:end] + cache = joinpath(path, "PyCall.ji") + backup = joinpath(path, "PyCall.ji.backup") + if !isfile(cache) && isfile(backup) + mv(backup, cache) + end + rm(backup; force=true) + end + """) + # 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 diff --git a/julia/find_libpython.py b/julia/find_libpython.py new file mode 100755 index 00000000..bfcd8413 --- /dev/null +++ b/julia/find_libpython.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python + +""" +Locate libpython associated with this Python executable. +""" + +from __future__ import print_function, absolute_import + +from logging import getLogger +import ctypes.util +import os +import platform +import sys +import sysconfig + +logger = getLogger("find_libpython") + +SHLIB_SUFFIX = sysconfig.get_config_var("SHLIB_SUFFIX") +if SHLIB_SUFFIX is None: + if platform.system() == "Windows": + SHLIB_SUFFIX = ".dll" + elif platform.system() == "Darwin": + SHLIB_SUFFIX = ".dylib" + else: + SHLIB_SUFFIX = ".so" + + +def linked_libpython(): + """ + Find the linked libpython using dladdr (in *nix). + + Returns + ------- + path : str or None + A path to linked libpython. Return `None` if statically linked. + """ + if platform.system() == "Windows": + return _linked_libpython_windows() + return _linked_libpython_unix() + + +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), + ] + + +def _linked_libpython_unix(): + libdl = ctypes.CDLL(ctypes.util.find_library("dl")) + libdl.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(Dl_info)] + libdl.dladdr.restype = ctypes.c_int + + dlinfo = Dl_info() + retcode = libdl.dladdr( + ctypes.cast(ctypes.pythonapi.Py_GetVersion, ctypes.c_void_p), + ctypes.pointer(dlinfo)) + if retcode == 0: # means error + return None + path = os.path.realpath(dlinfo.dli_fname.decode()) + if path == os.path.realpath(sys.executable): + return None + return path + + +def _linked_libpython_windows(): + """ + Based on: https://stackoverflow.com/a/16659821 + """ + from ctypes.wintypes import HANDLE, LPWSTR, DWORD + + GetModuleFileName = ctypes.windll.kernel32.GetModuleFileNameW + GetModuleFileName.argtypes = [HANDLE, LPWSTR, DWORD] + GetModuleFileName.restype = DWORD + + MAX_PATH = 260 + try: + handle = ctypes.windll.kernel32.GetModuleHandleA(None) + buf = ctypes.create_unicode_buffer(MAX_PATH) + GetModuleFileName(handle, buf, MAX_PATH) + return buf.value + except (ValueError, OSError): + return None + + + +def library_name(name, suffix=SHLIB_SUFFIX, + is_windows=platform.system() == "Windows"): + """ + Convert a file basename `name` to a library name (no "lib" and ".so" etc.) + + >>> library_name("libpython3.7m.so") # doctest: +SKIP + 'python3.7m' + >>> library_name("libpython3.7m.so", suffix=".so", is_windows=False) + 'python3.7m' + >>> library_name("libpython3.7m.dylib", suffix=".dylib", is_windows=False) + 'python3.7m' + >>> library_name("python37.dll", suffix=".dll", is_windows=True) + 'python37' + """ + if not is_windows: + name = name[len("lib"):] + if suffix and name.endswith(suffix): + name = name[:-len(suffix)] + return name + + +def append_truthy(list, item): + if item: + list.append(item) + + +def libpython_candidates(suffix=SHLIB_SUFFIX): + """ + Iterate over candidate paths of libpython. + + Yields + ------ + path : str or None + Candidate path to libpython. The path may not be a fullpath + and may not exist. + """ + + yield linked_libpython() + + is_windows = platform.system() == "Windows" + + # List candidates for libpython basenames + lib_basenames = [] + append_truthy(lib_basenames, sysconfig.get_config_var("LDLIBRARY")) + + LIBRARY = sysconfig.get_config_var("LIBRARY") + if LIBRARY: + lib_basenames.append(os.path.splitext(LIBRARY)[0] + suffix) + + dlprefix = "" if is_windows else "lib" + sysdata = dict( + v=sys.version_info, + # VERSION is X.Y in Linux/macOS and XY in Windows: + VERSION=(sysconfig.get_config_var("VERSION") or + "{v.major}.{v.minor}".format(v=sys.version_info)), + ABIFLAGS=(sysconfig.get_config_var("ABIFLAGS") or + sysconfig.get_config_var("abiflags") or ""), + ) + lib_basenames.extend(dlprefix + p + suffix for p in [ + "python{VERSION}{ABIFLAGS}".format(**sysdata), + "python{VERSION}".format(**sysdata), + "python{v.major}".format(**sysdata), + "python", + ]) + + # List candidates for directories in which libpython may exist + lib_dirs = [] + append_truthy(lib_dirs, sysconfig.get_config_var("LIBDIR")) + + if is_windows: + lib_dirs.append(os.path.join(os.path.dirname(sys.executable))) + else: + lib_dirs.append(os.path.join( + os.path.dirname(os.path.dirname(sys.executable)), + "lib")) + + # For macOS: + append_truthy(lib_dirs, sysconfig.get_config_var("PYTHONFRAMEWORKPREFIX")) + + lib_dirs.append(sys.exec_prefix) + lib_dirs.append(os.path.join(sys.exec_prefix, "lib")) + + for directory in lib_dirs: + for basename in lib_basenames: + yield os.path.join(directory, basename) + + # In macOS and Windows, ctypes.util.find_library returns a full path: + for basename in lib_basenames: + yield ctypes.util.find_library(library_name(basename)) + + +def normalize_path(path, suffix=SHLIB_SUFFIX): + """ + Normalize shared library `path` to a real path. + + If `path` is not a full path, `None` is returned. If `path` does + not exists, append `SHLIB_SUFFIX` and check if it exists. + Finally, the path is canonicalized by following the symlinks. + + Parameters + ---------- + path : str ot None + A candidate path to a shared library. + """ + if not path: + return None + if not os.path.isabs(path): + return None + if os.path.exists(path): + return os.path.realpath(path) + if os.path.exists(path + suffix): + return os.path.realpath(path + suffix) + return None + + +def finding_libpython(): + """ + Iterate over existing libpython paths. + + The first item is likely to be the best one. It may yield + duplicated paths. + + Yields + ------ + path : str + Existing path to a libpython. + """ + for path in libpython_candidates(): + logger.debug("Candidate: %s", path) + normalized = normalize_path(path) + logger.debug("Normalized: %s", normalized) + if normalized: + logger.debug("Found: %s", normalized) + yield normalized + + +def find_libpython(): + """ + Return a path (`str`) to libpython or `None` if not found. + + Parameters + ---------- + path : str or None + Existing path to the (supposedly) correct libpython. + """ + for path in finding_libpython(): + return os.path.realpath(path) + + +def cli_find_libpython(verbose, list_all): + import logging + # Importing `logging` module here so that using `logging.debug` + # instead of `logger.debug` outside of this function becomes an + # error. + + if verbose: + logging.basicConfig(level=logging.DEBUG) + + if list_all: + for path in finding_libpython(): + print(path) + return + + path = find_libpython() + if path is None: + return 1 + print(path, end="") + + +def main(args=None): + import argparse + parser = argparse.ArgumentParser( + description=__doc__) + parser.add_argument( + "--verbose", "-v", action="store_true", + help="Print debugging information.") + parser.add_argument( + "--list-all", action="store_true", + help="Print list of all paths found.") + ns = parser.parse_args(args) + parser.exit(cli_find_libpython(**vars(ns))) + + +if __name__ == "__main__": + main() diff --git a/julia/with_rebuilt.py b/julia/with_rebuilt.py index 48ce7122..f483b930 100644 --- a/julia/with_rebuilt.py +++ b/julia/with_rebuilt.py @@ -27,6 +27,16 @@ def maybe_rebuild(rebuild, julia): using Pkg end Pkg.build("PyCall") + if VERSION < v"0.7.0" + pkgdir = Pkg.dir("PyCall") + else + modpath = Base.locate_package(Base.identify_package("PyCall")) + pkgdir = joinpath(dirname(modpath), "..") + end + logfile = joinpath(pkgdir, "deps", "build.log") + if isfile(logfile) + print(read(logfile, String)) + end """] print('Building PyCall.jl with PYTHON =', sys.executable) print(*build) diff --git a/test/test_utils.py b/test/test_utils.py index a86d146b..178ae473 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -2,17 +2,24 @@ Unit tests which can be done without loading `libjulia`. """ -import sys +import platform -import pytest +from julia.find_libpython import finding_libpython, linked_libpython +from julia.core import determine_if_statically_linked -from julia.core import is_different_exe +try: + unicode +except NameError: + unicode = str # for Python 3 -@pytest.mark.parametrize('pyprogramname, sys_executable, exe_differs', [ - (sys.executable, sys.executable, False), - (None, sys.executable, True), - ('/dev/null', sys.executable, True), -]) -def test_is_different_exe(pyprogramname, sys_executable, exe_differs): - assert is_different_exe(pyprogramname, sys_executable) == exe_differs +def test_finding_libpython_yield_type(): + paths = list(finding_libpython()) + assert set(map(type, paths)) <= {str, unicode} +# In a statically linked Python executable, no paths may be found. So +# let's just check returned type of finding_libpython. + + +def test_linked_libpython(): + if determine_if_statically_linked(): + assert linked_libpython() is not None diff --git a/tox.ini b/tox.ini index 459153cc..2713953e 100644 --- a/tox.ini +++ b/tox.ini @@ -3,12 +3,19 @@ envlist = py27, py36 [testenv] deps = - pytest + pytest != 3.7.3 + # Don't install 3.7.3 to avoid doctest failures in macOS + # https://github.com/pytest-dev/pytest/pull/3893#issuecomment-416560866 + pytest-cov numpy ipython mock commands = + python -m julia.find_libpython --list-all --verbose + # Print libpython candidates found by `find_libpython`. It may be + # useful for debugging. + python -m julia.with_rebuilt -- python -m pytest {posargs} # Using "python -m pytest" to exactly match the Python interpreter # used to build PyCall.jl via julia/with_rebuilt.py (when @@ -27,3 +34,9 @@ passenv = # See: https://coveralls-python.readthedocs.io/en/latest/usage/tox.html#travisci TRAVIS TRAVIS_* + +[pytest] +addopts = + --doctest-modules + --ignore=julia/fake-julia + --ignore=test/_star_import.py