link statically against libpython in BuildExecutable (hack to make it work if libpyth...
[cython.git] / Cython / Build / BuildExecutable.py
1 """
2 Compile a Python script into an executable that embeds CPython and run it.
3 Requires CPython to be built as a shared library ('libpythonX.Y').
4
5 Basic usage:
6
7     python cythonrun somefile.py [ARGS]
8 """
9
10 DEBUG = True
11
12 import sys
13 import os
14 from distutils import sysconfig
15
16 def get_config_var(name):
17     return sysconfig.get_config_var(name) or ''
18
19 INCDIR = sysconfig.get_python_inc()
20 LIBDIR1 = get_config_var('LIBDIR')
21 LIBDIR2 = get_config_var('LIBPL')
22 PYLIB = get_config_var('LIBRARY')
23
24 CC = get_config_var('CC')
25 CFLAGS = get_config_var('CFLAGS') + ' ' + os.environ.get('CFLAGS', '')
26 LINKCC = get_config_var('LINKCC')
27 LINKFORSHARED = get_config_var('LINKFORSHARED')
28 LIBS = get_config_var('LIBS')
29 SYSLIBS = get_config_var('SYSLIBS')
30
31 def _debug(msg, *args):
32     if DEBUG:
33         if args:
34             msg = msg % args
35         sys.stderr.write(msg + '\n')
36
37 def dump_config():
38     _debug('INCDIR: %s', INCDIR)
39     _debug('LIBDIR1: %s', LIBDIR1)
40     _debug('LIBDIR2: %s', LIBDIR2)
41     _debug('PYLIB: %s', PYLIB)
42     _debug('CC: %s', CC)
43     _debug('CFLAGS: %s', CFLAGS)
44     _debug('LINKCC: %s', LINKCC)
45     _debug('LINKFORSHARED: %s', LINKFORSHARED)
46     _debug('LIBS: %s', LIBS)
47     _debug('SYSLIBS: %s', SYSLIBS)
48
49 def runcmd(cmd, shell=True):
50     if shell:
51         cmd = ' '.join(cmd)
52         _debug(cmd)
53     else:
54         _debug(' '.join(cmd))
55
56     try:
57         import subprocess
58     except ImportError: # Python 2.3 ...
59         returncode = os.system(cmd)
60     else:
61         returncode = subprocess.call(cmd, shell=shell)
62     
63     if returncode:
64         sys.exit(returncode)
65
66 def clink(basename):
67     runcmd([LINKCC, '-o', basename, basename+'.o', '-L'+LIBDIR1, '-L'+LIBDIR2,
68             os.path.join(LIBDIR1, PYLIB)]
69            + LIBS.split() + SYSLIBS.split() + LINKFORSHARED.split())
70
71 def ccompile(basename):
72     runcmd([CC, '-c', '-o', basename+'.o', basename+'.c', '-I' + INCDIR] + CFLAGS.split())
73
74 def cycompile(input_file, options=()):
75     from Cython.Compiler import Version, CmdLine, Main
76     options, sources = CmdLine.parse_command_line(list(options or ()) + ['--embed', input_file])
77     _debug('Using Cython %s to compile %s', Version.version, input_file)
78     result = Main.compile(sources, options)
79     if result.num_errors > 0:
80         sys.exit(1)
81
82 def exec_file(basename, args=()):
83     runcmd([os.path.abspath(basename)] + list(args), shell=False)
84
85 def build(input_file, compiler_args=()):
86     """
87     Build an executable program from a Cython module.
88
89     Returns the name of the executable file.
90     """
91     basename = os.path.splitext(input_file)[0]
92     cycompile(input_file, compiler_args)
93     ccompile(basename)
94     clink(basename)
95     return basename
96
97 def build_and_run(args):
98     """
99     Build an executable program from a Cython module and runs it.
100
101     Arguments after the module name will be passed verbatimely to the
102     program.
103     """
104     cy_args = []
105     last_arg = None
106     for i, arg in enumerate(args):
107         if arg.startswith('-'):
108             cy_args.append(arg)
109         elif last_arg in ('-X', '--directive'):
110             cy_args.append(arg)
111         else:
112             input_file = arg
113             args = args[i+1:]
114             break
115         last_arg = arg
116     else:
117         raise ValueError('no input file provided')
118
119     program_name = build(input_file, cy_args)
120     exec_file(program_name, args)
121
122 if __name__ == '__main__':
123     build_and_run(sys.argv[1:])