fix left-over tabs in source files
[cython.git] / pyximport / pyxbuild.py
1 """Build a Pyrex file from .pyx source to .so loadable module using
2 the installed distutils infrastructure. Call:
3
4 out_fname = pyx_to_dll("foo.pyx")
5 """
6 import os
7
8 import distutils
9 from distutils.dist import Distribution
10 from distutils.errors import DistutilsArgError, DistutilsError, CCompilerError
11 from distutils.extension import Extension
12 from distutils.util import grok_environment_error
13 from Cython.Distutils import build_ext
14 import shutil
15
16 DEBUG = 0
17 def pyx_to_dll(filename, ext = None, force_rebuild = 0,
18                build_in_temp=False, pyxbuild_dir=None):
19     """Compile a PYX file to a DLL and return the name of the generated .so 
20        or .dll ."""
21     assert os.path.exists(filename)
22
23     path, name = os.path.split(filename)
24
25     if not ext:
26         modname, extension = os.path.splitext(name)
27         assert extension in (".pyx", ".py"), extension
28         ext = Extension(name=modname, sources=[filename])
29
30     if not pyxbuild_dir:
31         pyxbuild_dir = os.path.join(path, "_pyxbld")
32
33     if DEBUG:
34         quiet = "--verbose"
35     else:
36         quiet = "--quiet"
37     args = [quiet, "build_ext"]
38     if force_rebuild:
39         args.append("--force")
40     if build_in_temp:
41         args.append("--pyrex-c-in-temp")
42     dist = Distribution({"script_name": None, "script_args": args})
43     if not dist.ext_modules:
44         dist.ext_modules = []
45     dist.ext_modules.append(ext)
46     dist.cmdclass = {'build_ext': build_ext}
47     build = dist.get_command_obj('build')
48     build.build_base = pyxbuild_dir
49
50     try:
51         ok = dist.parse_command_line()
52     except DistutilsArgError, msg:
53         raise
54
55     if DEBUG:
56         print "options (after parsing command line):"
57         dist.dump_option_dicts()
58     assert ok
59
60
61     try:
62         dist.run_commands()
63         return dist.get_command_obj("build_ext").get_outputs()[0]
64     except KeyboardInterrupt:
65         raise SystemExit, "interrupted"
66     except (IOError, os.error), exc:
67         error = grok_environment_error(exc)
68
69         if DEBUG:
70             sys.stderr.write(error + "\n")
71             raise
72         else:
73             raise RuntimeError, error
74
75     except (DistutilsError,
76         CCompilerError), msg:
77         if DEBUG:
78             raise
79         else:
80             raise RuntimeError(repr(msg))
81
82 if __name__=="__main__":
83     pyx_to_dll("dummy.pyx")
84     import test
85