~elementary-apps/noise/trunk

« back to all changes in this revision

Viewing changes to .waf-1.6.2-ad4cc42bd7d347f7e283789e711b993f/waflib/Tools/python.py

  • Committer: Scott Ringwelski
  • Date: 2011-02-10 21:30:53 UTC
  • Revision ID: sgringwe@mtu.edu-20110210213053-d3c7mnexeref3cwj
sexy icons, sexy waf

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# encoding: utf-8
 
3
# WARNING! All changes made to this file will be lost!
 
4
 
 
5
import os,sys
 
6
from waflib import TaskGen,Utils,Utils,Runner,Options,Build,Errors
 
7
from waflib.Logs import debug,warn,info
 
8
from waflib.TaskGen import extension,taskgen_method,before,after,feature
 
9
from waflib.Configure import conf
 
10
FRAG='''
 
11
#ifdef __cplusplus
 
12
extern "C" {
 
13
#endif
 
14
        void Py_Initialize(void);
 
15
        void Py_Finalize(void);
 
16
#ifdef __cplusplus
 
17
}
 
18
#endif
 
19
int main()
 
20
{
 
21
   Py_Initialize();
 
22
   Py_Finalize();
 
23
   return 0;
 
24
}
 
25
'''
 
26
INST='''
 
27
import sys, py_compile
 
28
for pyfile in sys.argv[1:]:
 
29
        py_compile.compile(pyfile, pyfile + %r)
 
30
'''
 
31
def process_py(self,node):
 
32
        try:
 
33
                if not self.bld.is_install:
 
34
                        return
 
35
        except:
 
36
                return
 
37
        if not getattr(self,'install_path',None):
 
38
                self.install_path='${PYTHONDIR}'
 
39
        def inst_py(ctx):
 
40
                install_pyfile(self,node)
 
41
        self.bld.add_post_fun(inst_py)
 
42
def install_pyfile(self,node):
 
43
        tsk=self.bld.install_files(self.install_path,[node],postpone=False)
 
44
        path=os.path.join(tsk.get_install_path(),node.name)
 
45
        if self.bld.is_install<0:
 
46
                info("+ removing byte compiled python files")
 
47
                for x in'co':
 
48
                        try:
 
49
                                os.remove(path+x)
 
50
                        except OSError:
 
51
                                pass
 
52
        if self.bld.is_install>0:
 
53
                if self.env['PYC']or self.env['PYO']:
 
54
                        info("+ byte compiling %r"%path)
 
55
                if self.env['PYC']:
 
56
                        argv=[self.env['PYTHON'],'-c',INST%'c',path]
 
57
                        ret=Utils.subprocess.Popen(argv).wait()
 
58
                        if ret:
 
59
                                raise Errors.WafError('pyc compilation failed %r'%path)
 
60
                if self.env['PYO']:
 
61
                        argv=[self.env['PYTHON'],self.env['PYFLAGS_OPT'],'-c',INST%'o',path]
 
62
                        ret=Utils.subprocess.Popen(argv).wait()
 
63
                        if ret:
 
64
                                raise Errors.WafError('pyo compilation failed %r'%path)
 
65
def feature_py(self):
 
66
        pass
 
67
def init_pyext(self):
 
68
        if not getattr(self,'install_path',None):
 
69
                self.install_path='${PYTHONDIR}'
 
70
        self.uselib=self.to_list(getattr(self,'uselib',[]))
 
71
        if not'PYEXT'in self.uselib:
 
72
                self.uselib.append('PYEXT')
 
73
        self.env['cshlib_PATTERN']=self.env['cxxshlib_PATTERN']=self.env['pyext_PATTERN']
 
74
def init_pyembed(self):
 
75
        self.uselib=self.to_list(getattr(self,'uselib',[]))
 
76
        if not'PYEMBED'in self.uselib:
 
77
                self.uselib.append('PYEMBED')
 
78
def get_python_variables(conf,python_exe,variables,imports=['import sys']):
 
79
        program=list(imports)
 
80
        program.append('')
 
81
        for v in variables:
 
82
                program.append("print(repr(%s))"%v)
 
83
        os_env=dict(os.environ)
 
84
        try:
 
85
                del os_env['MACOSX_DEPLOYMENT_TARGET']
 
86
        except KeyError:
 
87
                pass
 
88
        try:
 
89
                out=conf.cmd_and_log(Utils.to_list(python_exe)+['-c','\n'.join(program)],env=os_env)
 
90
        except Errors.WafError:
 
91
                conf.fatal('The distutils module is unusable: install "python-devel"?')
 
92
        return_values=[]
 
93
        for s in out.split('\n'):
 
94
                s=s.strip()
 
95
                if not s:
 
96
                        continue
 
97
                if s=='None':
 
98
                        return_values.append(None)
 
99
                elif s[0]=="'"and s[-1]=="'":
 
100
                        return_values.append(s[1:-1])
 
101
                elif s[0].isdigit():
 
102
                        return_values.append(int(s))
 
103
                else:break
 
104
        return return_values
 
105
def check_python_headers(conf):
 
106
        if not conf.env['CC_NAME']and not conf.env['CXX_NAME']:
 
107
                conf.fatal('load a compiler first (gcc, g++, ..)')
 
108
        if not conf.env['PYTHON_VERSION']:
 
109
                conf.check_python_version()
 
110
        env=conf.env
 
111
        python=env['PYTHON']
 
112
        if not python:
 
113
                conf.fatal('could not find the python executable')
 
114
        v='prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
 
115
        try:
 
116
                lst=conf.get_python_variables(python,["get_config_var('%s')"%x for x in v],['from distutils.sysconfig import get_config_var'])
 
117
        except RuntimeError:
 
118
                conf.fatal("Python development headers not found (-v for details).")
 
119
        vals=['%s = %r'%(x,y)for(x,y)in zip(v,lst)]
 
120
        conf.to_log("Configuration returned from %r:\n%r\n"%(python,'\n'.join(vals)))
 
121
        dct=dict(zip(v,lst))
 
122
        x='MACOSX_DEPLOYMENT_TARGET'
 
123
        if dct[x]:
 
124
                conf.env[x]=conf.environ[x]=dct[x]
 
125
        env['pyext_PATTERN']='%s'+dct['SO']
 
126
        all_flags=dct['LDFLAGS']+' '+dct['LDSHARED']+' '+dct['CFLAGS']
 
127
        conf.parse_flags(all_flags,'PYEMBED')
 
128
        conf.parse_flags(all_flags,'PYEXT')
 
129
        result=None
 
130
        name='python'+env['PYTHON_VERSION']
 
131
        path=env['LIBPATH_PYEMBED']
 
132
        conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n"%path)
 
133
        result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
 
134
        if not result:
 
135
                conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n"%path)
 
136
                path=[dct['LIBDIR']or'']
 
137
                result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
 
138
        if not result:
 
139
                conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
 
140
                path=[dct['LIBPL']or'']
 
141
                result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
 
142
        if not result:
 
143
                conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
 
144
                path=[os.path.join(dct['prefix'],"libs")]
 
145
                name='python'+env['PYTHON_VERSION'].replace('.','')
 
146
                result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
 
147
        if result:
 
148
                env['LIBPATH_PYEMBED']=path
 
149
                env.append_value('LIB_PYEMBED',[name])
 
150
        else:
 
151
                conf.to_log("\n\n### LIB NOT FOUND\n")
 
152
        if(sys.platform=='win32'or sys.platform.startswith('os2')or sys.platform=='darwin'or dct['Py_ENABLE_SHARED']):
 
153
                env['LIBPATH_PYEXT']=env['LIBPATH_PYEMBED']
 
154
                env['LIB_PYEXT']=env['LIB_PYEMBED']
 
155
        num='.'.join(env['PYTHON_VERSION'].split('.')[:2])
 
156
        try:
 
157
                conf.find_program('python%s-config'%num,var='PYTHON_CONFIG')
 
158
        except conf.errors.ConfigurationError:
 
159
                conf.find_program('python-config-%s'%num,var='PYTHON_CONFIG',mandatory=False)
 
160
        includes=[]
 
161
        if conf.env.PYTHON_CONFIG:
 
162
                for incstr in conf.cmd_and_log("%s %s --includes"%(python,conf.env.PYTHON_CONFIG)).strip().split():
 
163
                        if(incstr.startswith('-I')or incstr.startswith('/I')):
 
164
                                incstr=incstr[2:]
 
165
                        if incstr not in includes:
 
166
                                includes.append(incstr)
 
167
                conf.to_log("Include path for Python extensions ""(found via python-config --includes): %r\n"%(includes,))
 
168
                env['INCLUDES_PYEXT']=includes
 
169
                env['INCLUDES_PYEMBED']=includes
 
170
        else:
 
171
                conf.to_log("Include path for Python extensions ""(found via distutils module): %r\n"%(dct['INCLUDEPY'],))
 
172
                env['INCLUDES_PYEXT']=[dct['INCLUDEPY']]
 
173
                env['INCLUDES_PYEMBED']=[dct['INCLUDEPY']]
 
174
        if env['CC_NAME']=='gcc':
 
175
                env.append_value('CFLAGS_PYEMBED',['-fno-strict-aliasing'])
 
176
                env.append_value('CFLAGS_PYEXT',['-fno-strict-aliasing'])
 
177
        if env['CXX_NAME']=='gcc':
 
178
                env.append_value('CXXFLAGS_PYEMBED',['-fno-strict-aliasing'])
 
179
                env.append_value('CXXFLAGS_PYEXT',['-fno-strict-aliasing'])
 
180
        conf.check(header_name='Python.h',define_name='HAVE_PYTHON_H',uselib='PYEMBED',fragment=FRAG,errmsg='Could not find the python development headers')
 
181
def check_python_version(conf,minver=None):
 
182
        assert minver is None or isinstance(minver,tuple)
 
183
        python=conf.env['PYTHON']
 
184
        if not python:
 
185
                conf.fatal('could not find the python executable')
 
186
        cmd=[python,'-c','import sys\nfor x in sys.version_info: print(str(x))']
 
187
        debug('python: Running python command %r'%cmd)
 
188
        lines=conf.cmd_and_log(cmd).split()
 
189
        assert len(lines)==5,"found %i lines, expected 5: %r"%(len(lines),lines)
 
190
        pyver_tuple=(int(lines[0]),int(lines[1]),int(lines[2]),lines[3],int(lines[4]))
 
191
        result=(minver is None)or(pyver_tuple>=minver)
 
192
        if result:
 
193
                pyver='.'.join([str(x)for x in pyver_tuple[:2]])
 
194
                conf.env['PYTHON_VERSION']=pyver
 
195
                if'PYTHONDIR'in conf.environ:
 
196
                        pydir=conf.environ['PYTHONDIR']
 
197
                else:
 
198
                        if sys.platform=='win32':
 
199
                                (python_LIBDEST,pydir)=conf.get_python_variables(python,["get_config_var('LIBDEST')","get_python_lib(standard_lib=0, prefix=%r)"%conf.env['PREFIX']],['from distutils.sysconfig import get_config_var, get_python_lib'])
 
200
                        else:
 
201
                                python_LIBDEST=None
 
202
                                (pydir,)=conf.get_python_variables(python,["get_python_lib(standard_lib=0, prefix=%r)"%conf.env['PREFIX']],['from distutils.sysconfig import get_config_var, get_python_lib'])
 
203
                        if python_LIBDEST is None:
 
204
                                if conf.env['LIBDIR']:
 
205
                                        python_LIBDEST=os.path.join(conf.env['LIBDIR'],"python"+pyver)
 
206
                                else:
 
207
                                        python_LIBDEST=os.path.join(conf.env['PREFIX'],"lib","python"+pyver)
 
208
                if hasattr(conf,'define'):
 
209
                        conf.define('PYTHONDIR',pydir)
 
210
                conf.env['PYTHONDIR']=pydir
 
211
        pyver_full='.'.join(map(str,pyver_tuple[:3]))
 
212
        if minver is None:
 
213
                conf.msg('Checking for python version',pyver_full)
 
214
        else:
 
215
                minver_str='.'.join(map(str,minver))
 
216
                conf.msg('Checking for python version',pyver_tuple,">= %s"%(minver_str,)and'GREEN'or'YELLOW')
 
217
        if not result:
 
218
                conf.fatal('The python version is too old, expecting %r'%(minver,))
 
219
def check_python_module(conf,module_name):
 
220
        conf.start_msg('Python module %s'%module_name)
 
221
        try:
 
222
                conf.cmd_and_log([conf.env['PYTHON'],'-c','import %s\nprint(1)\n'%module_name])
 
223
        except:
 
224
                conf.end_msg(False)
 
225
                conf.fatal('Could not find the python module %r'%module_name)
 
226
        conf.end_msg(True)
 
227
def configure(conf):
 
228
        try:
 
229
                conf.find_program('python',var='PYTHON')
 
230
        except conf.errors.ConfigurationError:
 
231
                warn("could not find a python executable, setting to sys.executable '%s'"%sys.executable)
 
232
                conf.env.PYTHON=sys.executable
 
233
        if conf.env.PYTHON!=sys.executable:
 
234
                warn("python executable '%s' different from sys.executable '%s'"%(conf.env.PYTHON,sys.executable))
 
235
        v=conf.env
 
236
        v['PYCMD']='"import sys, py_compile;py_compile.compile(sys.argv[1], sys.argv[2])"'
 
237
        v['PYFLAGS']=''
 
238
        v['PYFLAGS_OPT']='-O'
 
239
        v['PYC']=getattr(Options.options,'pyc',1)
 
240
        v['PYO']=getattr(Options.options,'pyo',1)
 
241
def options(opt):
 
242
        opt.add_option('--nopyc',action='store_false',default=1,help='Do not install bytecode compiled .pyc files (configuration) [Default:install]',dest='pyc')
 
243
        opt.add_option('--nopyo',action='store_false',default=1,help='Do not install optimised compiled .pyo files (configuration) [Default:install]',dest='pyo')
 
244
 
 
245
extension('.py')(process_py)
 
246
feature('py')(feature_py)
 
247
feature('pyext')(init_pyext)
 
248
before('propagate_uselib_vars','apply_link')(init_pyext)
 
249
before('propagate_uselib_vars')(init_pyembed)
 
250
feature('pyembed')(init_pyembed)
 
251
conf(get_python_variables)
 
252
conf(check_python_headers)
 
253
conf(check_python_version)
 
254
conf(check_python_module)
 
 
b'\\ No newline at end of file'