pyximport.py 23 KB
Newer Older
1
"""
2
Import hooks; when installed with the install() function, these hooks
3 4 5 6
allow importing .pyx files as if they were Python modules.

If you want the hook installed every time you run Python
you can add it to your Python version by adding these lines to
7
sitecustomize.py (which you can create from scratch in site-packages
8
if it doesn't exist there or somewhere else on your python path)::
9

10 11
    import pyximport
    pyximport.install()
12

13 14
For instance on the Mac with a non-system Python 2.3, you could create
sitecustomize.py with only those two lines at
15 16
/usr/local/lib/python2.3/site-packages/sitecustomize.py .

17 18 19 20
A custom distutils.core.Extension instance and setup() args
(Distribution) for for the build can be defined by a <modulename>.pyxbld
file like:

sbyrnes321's avatar
sbyrnes321 committed
21
# examplemod.pyxbld
22 23 24 25 26 27 28 29 30 31 32
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name = modname,
                     sources=[pyxfilename, 'hello.c'],
                     include_dirs=['/myinclude'] )
def make_setup_args():
    return dict(script_args=["--compiler=mingw32"])

Extra dependencies can be defined by a <modulename>.pyxdep .
See README.

33 34 35 36 37 38 39 40 41 42 43
Since Cython 0.11, the :mod:`pyximport` module also has experimental
compilation support for normal Python modules.  This allows you to
automatically run Cython on every .pyx and .py module that Python
imports, including parts of the standard library and installed
packages.  Cython will still fail to compile a lot of Python modules,
in which case the import mechanism will fall back to loading the
Python source modules instead.  The .py import mechanism is installed
like this::

    pyximport.install(pyimport = True)

44 45 46
Running this module as a top-level script will run a test and then print
the documentation.

47
This code is based on the Py2.3+ import protocol as described in PEP 302.
48
"""
49

50 51
import glob
import imp
52 53 54
import os
import sys
from zipimport import zipimporter, ZipImportError
Stefan Behnel's avatar
Stefan Behnel committed
55

56 57 58 59 60 61
mod_name = "pyximport"

PYX_EXT = ".pyx"
PYXDEP_EXT = ".pyxdep"
PYXBLD_EXT = ".pyxbld"

62 63
DEBUG_IMPORT = False

Stefan Behnel's avatar
Stefan Behnel committed
64

65 66 67 68 69
def _print(message, args):
    if args:
        message = message % args
    print(message)

Stefan Behnel's avatar
Stefan Behnel committed
70

71 72 73 74
def _debug(message, *args):
    if DEBUG_IMPORT:
        _print(message, args)

Stefan Behnel's avatar
Stefan Behnel committed
75

76 77 78
def _info(message, *args):
    _print(message, args)

Stefan Behnel's avatar
Stefan Behnel committed
79 80

# Performance problem: for every PYX file that is imported, we will
81 82
# invoke the whole distutils infrastructure even if the module is
# already built. It might be more efficient to only do it when the
83 84
# mod time of the .pyx is newer than the mod time of the .so but
# the question is how to get distutils to tell me the name of the .so
luz.paz's avatar
luz.paz committed
85
# before it builds it. Maybe it is easy...but maybe the performance
86 87 88 89
# issue isn't real.
def _load_pyrex(name, filename):
    "Load a pyrex file given a name and filename."

Stefan Behnel's avatar
Stefan Behnel committed
90

91
def get_distutils_extension(modname, pyxfilename, language_level=None):
92 93 94 95
#    try:
#        import hashlib
#    except ImportError:
#        import md5 as hashlib
96
#    extra = "_" + hashlib.md5(open(pyxfilename).read()).hexdigest()
97
#    modname = modname + extra
98
    extension_mod,setup_args = handle_special_build(modname, pyxfilename)
99
    if not extension_mod:
100 101 102 103
        if not isinstance(pyxfilename, str):
            # distutils is stupid in Py2 and requires exactly 'str'
            # => encode accidentally coerced unicode strings back to str
            pyxfilename = pyxfilename.encode(sys.getfilesystemencoding())
104
        from distutils.extension import Extension
105
        extension_mod = Extension(name = modname, sources=[pyxfilename])
106 107
        if language_level is not None:
            extension_mod.cython_directives = {'language_level': language_level}
108
    return extension_mod,setup_args
109

Stefan Behnel's avatar
Stefan Behnel committed
110

111 112
def handle_special_build(modname, pyxfilename):
    special_build = os.path.splitext(pyxfilename)[0] + PYXBLD_EXT
113 114
    ext = None
    setup_args={}
115
    if os.path.exists(special_build):
116 117
        # globls = {}
        # locs = {}
118 119
        # execfile(special_build, globls, locs)
        # ext = locs["make_ext"](modname, pyxfilename)
120
        mod = imp.load_source("XXXX", special_build, open(special_build))
121 122 123
        make_ext = getattr(mod,'make_ext',None)
        if make_ext:
            ext = make_ext(modname, pyxfilename)
Stefan Behnel's avatar
Stefan Behnel committed
124 125
            assert ext and ext.sources, "make_ext in %s did not return Extension" % special_build
        make_setup_args = getattr(mod, 'make_setup_args',None)
126 127
        if make_setup_args:
            setup_args = make_setup_args()
128
            assert isinstance(setup_args,dict), ("make_setup_args in %s did not return a dict"
129
                                         % special_build)
130
        assert set or setup_args, ("neither make_ext nor make_setup_args %s"
131
                                         % special_build)
132
        ext.sources = [os.path.join(os.path.dirname(special_build), source)
133
                       for source in ext.sources]
134
    return ext, setup_args
135

Stefan Behnel's avatar
Stefan Behnel committed
136

137
def handle_dependencies(pyxfilename):
138
    testing = '_test_files' in globals()
139 140 141 142 143
    dependfile = os.path.splitext(pyxfilename)[0] + PYXDEP_EXT

    # by default let distutils decide whether to rebuild on its own
    # (it has a better idea of what the output file will be)

144
    # but we know more about dependencies so force a rebuild if
145 146
    # some of the dependencies are newer than the pyxfile.
    if os.path.exists(dependfile):
147 148 149 150 151 152 153 154
        depends = open(dependfile).readlines()
        depends = [depend.strip() for depend in depends]

        # gather dependencies in the "files" variable
        # the dependency file is itself a dependency
        files = [dependfile]
        for depend in depends:
            fullpath = os.path.join(os.path.dirname(dependfile),
155
                                    depend)
156 157 158
            files.extend(glob.glob(fullpath))

        # only for unit testing to see we did the right thing
159 160
        if testing:
            _test_files[:] = []  #$pycheck_no
161 162 163 164 165

        # if any file that the pyxfile depends upon is newer than
        # the pyx file, 'touch' the pyx file so that distutils will
        # be tricked into rebuilding it.
        for file in files:
166
            from distutils.dep_util import newer
167
            if newer(file, pyxfilename):
168
                _debug("Rebuilding %s because of %s", pyxfilename, file)
169 170
                filetime = os.path.getmtime(file)
                os.utime(pyxfilename, (filetime, filetime))
171 172
                if testing:
                    _test_files.append(file)
173

Stefan Behnel's avatar
Stefan Behnel committed
174

175
def build_module(name, pyxfilename, pyxbuild_dir=None, inplace=False, language_level=None):
Stefan Behnel's avatar
Stefan Behnel committed
176
    assert os.path.exists(pyxfilename), "Path does not exist: %s" % pyxfilename
177 178
    handle_dependencies(pyxfilename)

Stefan Behnel's avatar
Stefan Behnel committed
179 180 181
    extension_mod, setup_args = get_distutils_extension(name, pyxfilename, language_level)
    build_in_temp = pyxargs.build_in_temp
    sargs = pyxargs.setup_args.copy()
182
    sargs.update(setup_args)
Stefan Behnel's avatar
Stefan Behnel committed
183
    build_in_temp = sargs.pop('build_in_temp',build_in_temp)
184

185
    from . import pyxbuild
186
    so_path = pyxbuild.pyx_to_dll(pyxfilename, extension_mod,
187 188 189
                                  build_in_temp=build_in_temp,
                                  pyxbuild_dir=pyxbuild_dir,
                                  setup_args=sargs,
190
                                  inplace=inplace,
191
                                  reload_support=pyxargs.reload_support)
192
    assert os.path.exists(so_path), "Cannot find: %s" % so_path
193

xqat's avatar
xqat committed
194
    junkpath = os.path.join(os.path.dirname(so_path), name+"_*") #very dangerous with --inplace ? yes, indeed, trying to eat my files ;)
195 196
    junkstuff = glob.glob(junkpath)
    for path in junkstuff:
Stefan Behnel's avatar
Stefan Behnel committed
197
        if path != so_path:
198 199 200
            try:
                os.remove(path)
            except IOError:
201
                _info("Couldn't remove %s", path)
202 203 204

    return so_path

Stefan Behnel's avatar
Stefan Behnel committed
205

206
def load_module(name, pyxfilename, pyxbuild_dir=None, is_package=False,
207
                build_inplace=False, language_level=None, so_path=None):
208
    try:
209 210 211 212 213 214 215
        if so_path is None:
            if is_package:
                module_name = name + '.__init__'
            else:
                module_name = name
            so_path = build_module(module_name, pyxfilename, pyxbuild_dir,
                                   inplace=build_inplace, language_level=language_level)
216
        mod = imp.load_dynamic(name, so_path)
217
        if is_package and not hasattr(mod, '__path__'):
218
            mod.__path__ = [os.path.dirname(so_path)]
219
        assert mod.__file__ == so_path, (mod.__file__, so_path)
Stefan Behnel's avatar
Stefan Behnel committed
220
    except Exception:
221 222 223 224 225
        if pyxargs.load_py_module_on_import_failure and pyxfilename.endswith('.py'):
            # try to fall back to normal import
            mod = imp.load_source(name, pyxfilename)
            assert mod.__file__ in (pyxfilename, pyxfilename+'c', pyxfilename+'o'), (mod.__file__, pyxfilename)
        else:
226
            tb = sys.exc_info()[2]
227
            import traceback
228 229 230 231 232 233
            exc = ImportError("Building module %s failed: %s" % (
                name, traceback.format_exception_only(*sys.exc_info()[:2])))
            if sys.version_info[0] >= 3:
                raise exc.with_traceback(tb)
            else:
                exec("raise exc, None, tb", {'exc': exc, 'tb': tb})
234 235
    return mod

236 237 238 239

# import hooks

class PyxImporter(object):
240 241
    """A meta-path importer for .pyx files.
    """
242 243
    def __init__(self, extension=PYX_EXT, pyxbuild_dir=None, inplace=False,
                 language_level=None):
244 245
        self.extension = extension
        self.pyxbuild_dir = pyxbuild_dir
246
        self.inplace = inplace
247
        self.language_level = language_level
248 249

    def find_module(self, fullname, package_path=None):
250
        if fullname in sys.modules  and  not pyxargs.reload_support:
251
            return None  # only here when reload()
252 253 254 255

        # package_path might be a _NamespacePath. Convert that into a list...
        if package_path is not None and not isinstance(package_path, list):
            package_path = list(package_path)
256 257 258
        try:
            fp, pathname, (ext,mode,ty) = imp.find_module(fullname,package_path)
            if fp: fp.close()  # Python should offer a Default-Loader to avoid this double find/open!
259 260 261 262 263
            if pathname and ty == imp.PKG_DIRECTORY:
                pkg_file = os.path.join(pathname, '__init__'+self.extension)
                if os.path.isfile(pkg_file):
                    return PyxLoader(fullname, pathname,
                        init_path=pkg_file,
264
                        pyxbuild_dir=self.pyxbuild_dir,
265 266
                        inplace=self.inplace,
                        language_level=self.language_level)
Stefan Behnel's avatar
Stefan Behnel committed
267
            if pathname and pathname.endswith(self.extension):
268
                return PyxLoader(fullname, pathname,
269
                                 pyxbuild_dir=self.pyxbuild_dir,
270 271
                                 inplace=self.inplace,
                                 language_level=self.language_level)
272
            if ty != imp.C_EXTENSION: # only when an extension, check if we have a .pyx next!
273 274 275 276 277 278
                return None

            # find .pyx fast, when .so/.pyd exist --inplace
            pyxpath = os.path.splitext(pathname)[0]+self.extension
            if os.path.isfile(pyxpath):
                return PyxLoader(fullname, pyxpath,
279
                                 pyxbuild_dir=self.pyxbuild_dir,
280 281
                                 inplace=self.inplace,
                                 language_level=self.language_level)
282

283 284
            # .so/.pyd's on PATH should not be remote from .pyx's
            # think no need to implement PyxArgs.importer_search_remote here?
285

286 287 288 289
        except ImportError:
            pass

        # searching sys.path ...
290

291
        #if DEBUG_IMPORT:  print "SEARCHING", fullname, package_path
292 293 294

        mod_parts = fullname.split('.')
        module_name = mod_parts[-1]
295
        pyx_module_name = module_name + self.extension
296

297 298 299 300
        # this may work, but it returns the file content, not its path
        #import pkgutil
        #pyx_source = pkgutil.get_data(package, pyx_module_name)

301
        paths = package_path or sys.path
302
        for path in paths:
303
            pyx_data = None
304 305
            if not path:
                path = os.getcwd()
306
            elif os.path.isfile(path):
Sergei Lebedev's avatar
Sergei Lebedev committed
307 308
                try:
                    zi = zipimporter(path)
309 310
                    pyx_data = zi.get_data(pyx_module_name)
                except (ZipImportError, IOError, OSError):
Sergei Lebedev's avatar
Sergei Lebedev committed
311
                    continue  # Module not found.
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
                # unzip the imported file into the build dir
                # FIXME: can interfere with later imports if build dir is in sys.path and comes before zip file
                path = self.pyxbuild_dir
            elif not os.path.isabs(path):
                path = os.path.abspath(path)

            pyx_module_path = os.path.join(path, pyx_module_name)
            if pyx_data is not None:
                if not os.path.exists(path):
                    try:
                        os.makedirs(path)
                    except OSError:
                        # concurrency issue?
                        if not os.path.exists(path):
                            raise
                with open(pyx_module_path, "wb") as f:
                    f.write(pyx_data)
            elif not os.path.isfile(pyx_module_path):
                continue  # Module not found.
Sergei Lebedev's avatar
Sergei Lebedev committed
331 332 333 334 335

            return PyxLoader(fullname, pyx_module_path,
                             pyxbuild_dir=self.pyxbuild_dir,
                             inplace=self.inplace,
                             language_level=self.language_level)
336

337
        # not found, normal package, not a .pyx file, none of our business
338
        _debug("%s not found" % fullname)
339 340
        return None

Stefan Behnel's avatar
Stefan Behnel committed
341

342 343 344
class PyImporter(PyxImporter):
    """A meta-path importer for normal .py files.
    """
345 346 347
    def __init__(self, pyxbuild_dir=None, inplace=False, language_level=None):
        if language_level is None:
            language_level = sys.version_info[0]
348
        self.super = super(PyImporter, self)
349 350
        self.super.__init__(extension='.py', pyxbuild_dir=pyxbuild_dir, inplace=inplace,
                            language_level=language_level)
351
        self.uncompilable_modules = {}
352 353
        self.blocked_modules = ['Cython', 'pyxbuild', 'pyximport.pyxbuild',
                                'distutils.extension', 'distutils.sysconfig']
354 355 356 357 358 359 360 361 362

    def find_module(self, fullname, package_path=None):
        if fullname in sys.modules:
            return None
        if fullname.startswith('Cython.'):
            return None
        if fullname in self.blocked_modules:
            # prevent infinite recursion
            return None
363 364
        if _lib_loader.knows(fullname):
            return _lib_loader
365
        _debug("trying import of module '%s'", fullname)
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
        if fullname in self.uncompilable_modules:
            path, last_modified = self.uncompilable_modules[fullname]
            try:
                new_last_modified = os.stat(path).st_mtime
                if new_last_modified > last_modified:
                    # import would fail again
                    return None
            except OSError:
                # module is no longer where we found it, retry the import
                pass

        self.blocked_modules.append(fullname)
        try:
            importer = self.super.find_module(fullname, package_path)
            if importer is not None:
381 382 383 384 385 386 387
                if importer.init_path:
                    path = importer.init_path
                    real_name = fullname + '.__init__'
                else:
                    path = importer.path
                    real_name = fullname
                _debug("importer found path %s for module %s", path, real_name)
388
                try:
389 390 391 392 393 394 395 396 397
                    so_path = build_module(
                        real_name, path,
                        pyxbuild_dir=self.pyxbuild_dir,
                        language_level=self.language_level,
                        inplace=self.inplace)
                    _lib_loader.add_lib(fullname, path, so_path,
                                        is_package=bool(importer.init_path))
                    return _lib_loader
                except Exception:
398 399 400 401 402 403 404 405 406 407 408 409 410 411
                    if DEBUG_IMPORT:
                        import traceback
                        traceback.print_exc()
                    # build failed, not a compilable Python module
                    try:
                        last_modified = os.stat(path).st_mtime
                    except OSError:
                        last_modified = 0
                    self.uncompilable_modules[fullname] = (path, last_modified)
                    importer = None
        finally:
            self.blocked_modules.pop()
        return importer

Stefan Behnel's avatar
Stefan Behnel committed
412

413 414 415 416 417 418 419 420 421
class LibLoader(object):
    def __init__(self):
        self._libs = {}

    def load_module(self, fullname):
        try:
            source_path, so_path, is_package = self._libs[fullname]
        except KeyError:
            raise ValueError("invalid module %s" % fullname)
422
        _debug("Loading shared library module '%s' from %s", fullname, so_path)
423 424 425 426 427 428 429 430 431 432
        return load_module(fullname, source_path, so_path=so_path, is_package=is_package)

    def add_lib(self, fullname, path, so_path, is_package):
        self._libs[fullname] = (path, so_path, is_package)

    def knows(self, fullname):
        return fullname in self._libs

_lib_loader = LibLoader()

Stefan Behnel's avatar
Stefan Behnel committed
433

434
class PyxLoader(object):
435 436 437 438
    def __init__(self, fullname, path, init_path=None, pyxbuild_dir=None,
                 inplace=False, language_level=None):
        _debug("PyxLoader created for loading %s from %s (init path: %s)",
               fullname, path, init_path)
439 440 441
        self.fullname = fullname
        self.path, self.init_path = path, init_path
        self.pyxbuild_dir = pyxbuild_dir
442 443
        self.inplace = inplace
        self.language_level = language_level
444 445 446 447 448 449 450

    def load_module(self, fullname):
        assert self.fullname == fullname, (
            "invalid module, expected %s, got %s" % (
            self.fullname, fullname))
        if self.init_path:
            # package
Stefan Behnel's avatar
Stefan Behnel committed
451
            #print "PACKAGE", fullname
452
            module = load_module(fullname, self.init_path,
453
                                 self.pyxbuild_dir, is_package=True,
454 455
                                 build_inplace=self.inplace,
                                 language_level=self.language_level)
456 457
            module.__path__ = [self.path]
        else:
Stefan Behnel's avatar
Stefan Behnel committed
458
            #print "MODULE", fullname
459
            module = load_module(fullname, self.path,
460
                                 self.pyxbuild_dir,
461 462
                                 build_inplace=self.inplace,
                                 language_level=self.language_level)
463
        return module
464 465


466 467 468 469 470 471
#install args
class PyxArgs(object):
    build_dir=True
    build_in_temp=True
    setup_args={}   #None

Stefan Behnel's avatar
Stefan Behnel committed
472 473
##pyxargs=None

474 475 476 477 478 479 480 481 482 483 484 485 486

def _have_importers():
    has_py_importer = False
    has_pyx_importer = False
    for importer in sys.meta_path:
        if isinstance(importer, PyxImporter):
            if isinstance(importer, PyImporter):
                has_py_importer = True
            else:
                has_pyx_importer = True

    return has_py_importer, has_pyx_importer

Stefan Behnel's avatar
Stefan Behnel committed
487

488
def install(pyximport=True, pyimport=False, build_dir=None, build_in_temp=True,
489
            setup_args=None, reload_support=False,
490 491
            load_py_module_on_import_failure=False, inplace=False,
            language_level=None):
492 493 494
    """ Main entry point for pyxinstall.

    Call this to install the ``.pyx`` import hook in
495
    your meta-path for a single Python process.  If you want it to be
496
    installed whenever you use Python, add it to your ``sitecustomize``
497
    (as described above).
498

499 500 501 502
    :param pyximport: If set to False, does not try to import ``.pyx`` files.

    :param pyimport: You can pass ``pyimport=True`` to also
        install the ``.py`` import hook
503 504 505 506
        in your meta-path.  Note, however, that it is rather experimental,
        will not work at all for some ``.py`` files and packages, and will
        heavily slow down your imports due to search and compilation.
        Use at your own risk.
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

    :param build_dir: By default, compiled modules will end up in a ``.pyxbld``
        directory in the user's home directory.  Passing a different path
        as ``build_dir`` will override this.

    :param build_in_temp: If ``False``, will produce the C files locally. Working
        with complex dependencies and debugging becomes more easy. This
        can principally interfere with existing files of the same name.

    :param setup_args: Dict of arguments for Distribution.
        See ``distutils.core.setup()``.

    :param reload_support: Enables support for dynamic
        ``reload(my_module)``, e.g. after a change in the Cython code.
        Additional files ``<so_path>.reloadNN`` may arise on that account, when
        the previously loaded module file cannot be overwritten.

    :param load_py_module_on_import_failure: If the compilation of a ``.py``
        file succeeds, but the subsequent import fails for some reason,
        retry the import with the normal ``.py`` module instead of the
        compiled module.  Note that this may lead to unpredictable results
        for modules that change the system state during their import, as
        the second import will rerun these modifications in whatever state
        the system was left after the import of the compiled module
        failed.

    :param inplace: Install the compiled module
        (``.so`` for Linux and Mac / ``.pyd`` for Windows)
        next to the source file.

    :param language_level: The source language level to use: 2 or 3.
        The default is to use the language level of the current Python
        runtime for .py files and Py2 for ``.pyx`` files.
540
    """
541 542
    if setup_args is None:
        setup_args = {}
543
    if not build_dir:
544
        build_dir = os.path.join(os.path.expanduser('~'), '.pyxbld')
545

546 547 548 549 550 551
    global pyxargs
    pyxargs = PyxArgs()  #$pycheck_no
    pyxargs.build_dir = build_dir
    pyxargs.build_in_temp = build_in_temp
    pyxargs.setup_args = (setup_args or {}).copy()
    pyxargs.reload_support = reload_support
552
    pyxargs.load_py_module_on_import_failure = load_py_module_on_import_failure
553

554 555
    has_py_importer, has_pyx_importer = _have_importers()
    py_importer, pyx_importer = None, None
556 557

    if pyimport and not has_py_importer:
558 559
        py_importer = PyImporter(pyxbuild_dir=build_dir, inplace=inplace,
                                 language_level=language_level)
560
        # make sure we import Cython before we install the import hook
561
        import Cython.Compiler.Main, Cython.Compiler.Pipeline, Cython.Compiler.Optimize
562
        sys.meta_path.insert(0, py_importer)
563 564

    if pyximport and not has_pyx_importer:
565 566
        pyx_importer = PyxImporter(pyxbuild_dir=build_dir, inplace=inplace,
                                   language_level=language_level)
567
        sys.meta_path.append(pyx_importer)
568

569 570
    return py_importer, pyx_importer

Stefan Behnel's avatar
Stefan Behnel committed
571

572 573 574 575 576 577 578 579 580 581 582 583 584
def uninstall(py_importer, pyx_importer):
    """
    Uninstall an import hook.
    """
    try:
        sys.meta_path.remove(py_importer)
    except ValueError:
        pass

    try:
        sys.meta_path.remove(pyx_importer)
    except ValueError:
        pass
585

Stefan Behnel's avatar
Stefan Behnel committed
586

587
# MAIN
588 589 590 591 592 593 594 595 596 597 598 599

def show_docs():
    import __main__
    __main__.__name__ = mod_name
    for name in dir(__main__):
        item = getattr(__main__, name)
        try:
            setattr(item, "__module__", mod_name)
        except (AttributeError, TypeError):
            pass
    help(__main__)

Stefan Behnel's avatar
Stefan Behnel committed
600

601 602
if __name__ == '__main__':
    show_docs()