diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 2e89c25..0184eb0 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -23,14 +23,6 @@ jobs: - ubuntu-20.04 - macos-latest - windows-latest - include: - # https://github.com/diegoferigo/cmake-build-extension/issues/8 - - os: windows-latest - python-version: 3.8 - experimental: true - - os: windows-latest - python-version: 3.9 - experimental: true steps: diff --git a/examples/swig/setup.cfg b/examples/swig/setup.cfg index 4abef78..427bba7 100644 --- a/examples/swig/setup.cfg +++ b/examples/swig/setup.cfg @@ -20,7 +20,9 @@ packages = find: package_dir = =src python_requires = >=3.6 -install_requires = numpy +install_requires = + numpy + cmake-build-extension [options.packages.find] where = src diff --git a/examples/swig/setup.py b/examples/swig/setup.py index c3e4209..1ae5531 100644 --- a/examples/swig/setup.py +++ b/examples/swig/setup.py @@ -1,3 +1,4 @@ +import inspect import sys from pathlib import Path @@ -7,11 +8,21 @@ with open(Path(__file__).parent.absolute() / "README.md", encoding="utf-8") as f: long_description = f.read() +init_py = inspect.cleandoc( + """ + from cmake_build_extension import build_extension_env + + with build_extension_env(): + from . import bindings + """ +) + setup( ext_modules=[ CMakeExtension( name="mymath", install_prefix="mymath", + write_top_level_init=init_py, source_dir=str(Path(__file__).parent.absolute()), cmake_configure_options=[ f"-DPython3_ROOT_DIR={Path(sys.prefix)}", diff --git a/src/cmake_build_extension/__init__.py b/src/cmake_build_extension/__init__.py index f5501e7..e162cac 100644 --- a/src/cmake_build_extension/__init__.py +++ b/src/cmake_build_extension/__init__.py @@ -1,3 +1,48 @@ +import os +from contextlib import contextmanager +from pathlib import Path + from . import build_ext_option from .build_extension import BuildExtension from .cmake_extension import CMakeExtension + + +@contextmanager +def build_extension_env(): + """ + Creates a context in which build extensions can be imported. + + It fixes a change of behaviour of Python >= 3.8 in Windows: + https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew + + Other related resources: + + - https://stackoverflow.com/a/23805306 + - https://www.mail-archive.com/dev@subversion.apache.org/msg40414.html + + Example: + + .. code-block:: python + + from cmake_build_extension import build_extension_env + + with build_extension_env(): + from . import bindings + """ + + cookies = [] + + # Windows and Python >= 3.8 + if hasattr(os, "add_dll_directory"): + + for path in os.environ.get("PATH", "").split(os.pathsep): + + if path and Path(path).is_absolute() and Path(path).is_dir(): + cookies.append(os.add_dll_directory(path)) + + try: + yield + + finally: + for cookie in cookies: + cookie.close()