Removed pyrex.
[rox-lib.git] / python / rox / compile.py
blob6f1ff6917cdf777441e0794d27518645192e46d7
1 """Sometimes pure python code isn't enough. Either you need more speed or,
2 more often, you want to call some C library function for which there is no
3 python wrapper.
5 Pyrex extends python with support for C's type system, allowing it to compile
6 annotated python to fast C code. This module is a front-end to pyrex, a copy
7 of which is included with ROX-Lib.
9 To use it, create a source file (eg, 'mymodule.pyx'):
11 cdef extern int puts(char*)
13 def test():
14 print "Hello from python"
15 puts("Hello from C")
17 Then import this module from your program, compile the .pyx and then import
18 the resulting module:
20 from rox import compile
21 compile.compile('mymodule.pyx')
23 import mymodule
24 mymodule.test()
26 To find out more about what pyrex can do, see its web site:
28 http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
29 """
31 import pickle
32 import os.path
33 import rox
35 def compile(source, libraries = []):
36 """Compile this .pyx source file, creating a .so file in the same
37 directory. If the path is relative, rox.app_dir is prepended.
38 If an error occurs, it is reported in an error box and an exception
39 is thrown."""
40 source = os.path.join(rox.app_dir, source)
41 if not os.path.exists(os.path.join(source)):
42 raise Exception("Source file '%s' missing" % source)
43 dir = os.path.dirname(__file__)
44 args = pickle.dumps((source, libraries))
45 r, w = os.pipe()
46 child = os.fork()
47 if child == 0:
48 try:
49 os.close(r)
50 os.dup2(w, 1)
51 os.dup2(w, 2)
52 os.close(w)
53 os.chdir(dir)
55 os.execl('./setup.py', './setup.py', 'build_ext', '--inplace', '--quiet', args)
56 finally:
57 os._exit(1)
58 assert 0
59 os.close(w)
60 details = os.fdopen(r, 'r').read()
61 (pid, status) = os.waitpid(child, 0)
62 if status:
63 rox.alert('Error compiling %s:\n\n%s' % (source, details))
64 raise Exception('Compile failed')