cython_freeze 2.04 KB
Newer Older
1 2 3 4 5
#!/usr/bin/env python
"""
Create a C file for embedding one or more Cython source files.
Requires Cython 0.11.2 (or perhaps newer).

6
See Demos/freeze/README.rst for more details.
7 8
"""

9
import optparse
10

11
usage= '%prog [-o outfile] module [module ...]'
12 13
description = 'Create a C file for embedding Cython modules.'
p = optparse.OptionParser(usage=usage, description=description)
14 15
p.add_option('-o', '--output', metavar='FILE',
        help='write output to FILE instead of standard output')
16 17 18 19 20 21

options, args = p.parse_args()

if len(args) < 1:
    p.print_help()
    p.exit(1)
22

23 24 25 26 27
if options.output:
    import sys
    old_stdout = sys.stdout
    sys.stdout = open(options.output, 'w')

28 29 30
def format_modname(name):
    if name.endswith('.pyx'):
        name = name[:-4]
31 32
    elif name.endswith('.py'):
        name = name[:-3]
33 34
    return name.replace('.','_')

35
modules = [format_modname(x) for x in args]
36

37
print """\
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
#include <Python.h>
#include <stdio.h>
#include <stdlib.h>

#if PY_MAJOR_VERSION < 3
# define MODINIT(name)  init ## name
#else
# define MODINIT(name)  PyInit_ ## name
#endif
"""

for name in modules:
    print "PyMODINIT_FUNC MODINIT(%s) (void);" % name

print """
static struct _inittab inittab[] = {"""

for name in modules:
    print '    {"%(name)s", MODINIT(%(name)s)},' % {'name' : name}

print """    {NULL, NULL}
};

extern int __pyx_module_is_main_%(main)s;

#if PY_MAJOR_VERSION < 3 || (!defined(WIN32) && !defined(MS_WINDOWS))
int main(int argc, char** argv) {
#else
int wmain(int argc, wchar_t **argv) {
#endif
    int r = 0;
    PyObject *m = NULL;
    if (PyImport_ExtendInittab(inittab)) {
        fprintf(stderr, "No memory\\n");
        exit(1);
    }
    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    __pyx_module_is_main_%(main)s = 1;
    m = PyImport_ImportModule(inittab[0].name);
    if (!m) {
        r = 1;
        PyErr_Print(); /* This exits with the right code if SystemExit. */
82 83
        if (Py_FlushLine())
            PyErr_Clear();
84 85 86 87 88
    }
    Py_XDECREF(m);
    Py_Finalize();
    return r;
}
89
""" % {'main' : modules[0]},