python.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Thomas Nagy, 2007-2015 (ita)
  4. # Gustavo Carneiro (gjc), 2007
  5. """
  6. Support for Python, detect the headers and libraries and provide
  7. *use* variables to link C/C++ programs against them::
  8. def options(opt):
  9. opt.load('compiler_c python')
  10. def configure(conf):
  11. conf.load('compiler_c python')
  12. conf.check_python_version((2,4,2))
  13. conf.check_python_headers()
  14. def build(bld):
  15. bld.program(features='pyembed', source='a.c', target='myprog')
  16. bld.shlib(features='pyext', source='b.c', target='mylib')
  17. """
  18. import os, sys
  19. from waflib import Errors, Logs, Node, Options, Task, Utils
  20. from waflib.TaskGen import extension, before_method, after_method, feature
  21. from waflib.Configure import conf
  22. FRAG = '''
  23. #include <Python.h>
  24. #ifdef __cplusplus
  25. extern "C" {
  26. #endif
  27. void Py_Initialize(void);
  28. void Py_Finalize(void);
  29. #ifdef __cplusplus
  30. }
  31. #endif
  32. int main(int argc, char **argv)
  33. {
  34. (void)argc; (void)argv;
  35. Py_Initialize();
  36. Py_Finalize();
  37. return 0;
  38. }
  39. '''
  40. """
  41. Piece of C/C++ code used in :py:func:`waflib.Tools.python.check_python_headers`
  42. """
  43. INST = '''
  44. import sys, py_compile
  45. py_compile.compile(sys.argv[1], sys.argv[2], sys.argv[3], True)
  46. '''
  47. """
  48. Piece of Python code used in :py:class:`waflib.Tools.python.pyo` and :py:class:`waflib.Tools.python.pyc` for byte-compiling python files
  49. """
  50. DISTUTILS_IMP = ['from distutils.sysconfig import get_config_var, get_python_lib']
  51. @before_method('process_source')
  52. @feature('py')
  53. def feature_py(self):
  54. """
  55. Create tasks to byte-compile .py files and install them, if requested
  56. """
  57. self.install_path = getattr(self, 'install_path', '${PYTHONDIR}')
  58. install_from = getattr(self, 'install_from', None)
  59. if install_from and not isinstance(install_from, Node.Node):
  60. install_from = self.path.find_dir(install_from)
  61. self.install_from = install_from
  62. ver = self.env.PYTHON_VERSION
  63. if not ver:
  64. self.bld.fatal('Installing python files requires PYTHON_VERSION, try conf.check_python_version')
  65. if int(ver.replace('.', '')) > 31:
  66. self.install_32 = True
  67. @extension('.py')
  68. def process_py(self, node):
  69. """
  70. Add signature of .py file, so it will be byte-compiled when necessary
  71. """
  72. assert(hasattr(self, 'install_path')), 'add features="py"'
  73. # where to install the python file
  74. if self.install_path:
  75. if self.install_from:
  76. self.add_install_files(install_to=self.install_path, install_from=node, cwd=self.install_from, relative_trick=True)
  77. else:
  78. self.add_install_files(install_to=self.install_path, install_from=node, relative_trick=True)
  79. lst = []
  80. if self.env.PYC:
  81. lst.append('pyc')
  82. if self.env.PYO:
  83. lst.append('pyo')
  84. if self.install_path:
  85. if self.install_from:
  86. pyd = Utils.subst_vars("%s/%s" % (self.install_path, node.path_from(self.install_from)), self.env)
  87. else:
  88. pyd = Utils.subst_vars("%s/%s" % (self.install_path, node.path_from(self.path)), self.env)
  89. else:
  90. pyd = node.abspath()
  91. for ext in lst:
  92. if self.env.PYTAG and not self.env.NOPYCACHE:
  93. # __pycache__ installation for python 3.2 - PEP 3147
  94. name = node.name[:-3]
  95. pyobj = node.parent.get_bld().make_node('__pycache__').make_node("%s.%s.%s" % (name, self.env.PYTAG, ext))
  96. pyobj.parent.mkdir()
  97. else:
  98. pyobj = node.change_ext(".%s" % ext)
  99. tsk = self.create_task(ext, node, pyobj)
  100. tsk.pyd = pyd
  101. if self.install_path:
  102. self.add_install_files(install_to=os.path.dirname(pyd), install_from=pyobj, cwd=node.parent.get_bld(), relative_trick=True)
  103. class pyc(Task.Task):
  104. """
  105. Byte-compiling python files
  106. """
  107. color = 'PINK'
  108. def __str__(self):
  109. node = self.outputs[0]
  110. return node.path_from(node.ctx.launch_node())
  111. def run(self):
  112. cmd = [Utils.subst_vars('${PYTHON}', self.env), '-c', INST, self.inputs[0].abspath(), self.outputs[0].abspath(), self.pyd]
  113. ret = self.generator.bld.exec_command(cmd)
  114. return ret
  115. class pyo(Task.Task):
  116. """
  117. Byte-compiling python files
  118. """
  119. color = 'PINK'
  120. def __str__(self):
  121. node = self.outputs[0]
  122. return node.path_from(node.ctx.launch_node())
  123. def run(self):
  124. cmd = [Utils.subst_vars('${PYTHON}', self.env), Utils.subst_vars('${PYFLAGS_OPT}', self.env), '-c', INST, self.inputs[0].abspath(), self.outputs[0].abspath(), self.pyd]
  125. ret = self.generator.bld.exec_command(cmd)
  126. return ret
  127. @feature('pyext')
  128. @before_method('propagate_uselib_vars', 'apply_link')
  129. @after_method('apply_bundle')
  130. def init_pyext(self):
  131. """
  132. Change the values of *cshlib_PATTERN* and *cxxshlib_PATTERN* to remove the
  133. *lib* prefix from library names.
  134. """
  135. self.uselib = self.to_list(getattr(self, 'uselib', []))
  136. if not 'PYEXT' in self.uselib:
  137. self.uselib.append('PYEXT')
  138. # override shlib_PATTERN set by the osx module
  139. self.env.cshlib_PATTERN = self.env.cxxshlib_PATTERN = self.env.macbundle_PATTERN = self.env.pyext_PATTERN
  140. self.env.fcshlib_PATTERN = self.env.dshlib_PATTERN = self.env.pyext_PATTERN
  141. try:
  142. if not self.install_path:
  143. return
  144. except AttributeError:
  145. self.install_path = '${PYTHONARCHDIR}'
  146. @feature('pyext')
  147. @before_method('apply_link', 'apply_bundle')
  148. def set_bundle(self):
  149. """Mac-specific pyext extension that enables bundles from c_osx.py"""
  150. if Utils.unversioned_sys_platform() == 'darwin':
  151. self.mac_bundle = True
  152. @before_method('propagate_uselib_vars')
  153. @feature('pyembed')
  154. def init_pyembed(self):
  155. """
  156. Add the PYEMBED variable.
  157. """
  158. self.uselib = self.to_list(getattr(self, 'uselib', []))
  159. if not 'PYEMBED' in self.uselib:
  160. self.uselib.append('PYEMBED')
  161. @conf
  162. def get_python_variables(self, variables, imports=None):
  163. """
  164. Spawn a new python process to dump configuration variables
  165. :param variables: variables to print
  166. :type variables: list of string
  167. :param imports: one import by element
  168. :type imports: list of string
  169. :return: the variable values
  170. :rtype: list of string
  171. """
  172. if not imports:
  173. try:
  174. imports = self.python_imports
  175. except AttributeError:
  176. imports = DISTUTILS_IMP
  177. program = list(imports) # copy
  178. program.append('')
  179. for v in variables:
  180. program.append("print(repr(%s))" % v)
  181. os_env = dict(os.environ)
  182. try:
  183. del os_env['MACOSX_DEPLOYMENT_TARGET'] # see comments in the OSX tool
  184. except KeyError:
  185. pass
  186. try:
  187. out = self.cmd_and_log(self.env.PYTHON + ['-c', '\n'.join(program)], env=os_env)
  188. except Errors.WafError:
  189. self.fatal('The distutils module is unusable: install "python-devel"?')
  190. self.to_log(out)
  191. return_values = []
  192. for s in out.splitlines():
  193. s = s.strip()
  194. if not s:
  195. continue
  196. if s == 'None':
  197. return_values.append(None)
  198. elif (s[0] == "'" and s[-1] == "'") or (s[0] == '"' and s[-1] == '"'):
  199. return_values.append(eval(s))
  200. elif s[0].isdigit():
  201. return_values.append(int(s))
  202. else: break
  203. return return_values
  204. @conf
  205. def test_pyembed(self, mode, msg='Testing pyembed configuration'):
  206. self.check(header_name='Python.h', define_name='HAVE_PYEMBED', msg=msg,
  207. fragment=FRAG, errmsg='Could not build a python embedded interpreter',
  208. features='%s %sprogram pyembed' % (mode, mode))
  209. @conf
  210. def test_pyext(self, mode, msg='Testing pyext configuration'):
  211. self.check(header_name='Python.h', define_name='HAVE_PYEXT', msg=msg,
  212. fragment=FRAG, errmsg='Could not build python extensions',
  213. features='%s %sshlib pyext' % (mode, mode))
  214. @conf
  215. def python_cross_compile(self, features='pyembed pyext'):
  216. """
  217. For cross-compilation purposes, it is possible to bypass the normal detection and set the flags that you want:
  218. PYTHON_VERSION='3.4' PYTAG='cpython34' pyext_PATTERN="%s.so" PYTHON_LDFLAGS='-lpthread -ldl' waf configure
  219. The following variables are used:
  220. PYTHON_VERSION required
  221. PYTAG required
  222. PYTHON_LDFLAGS required
  223. pyext_PATTERN required
  224. PYTHON_PYEXT_LDFLAGS
  225. PYTHON_PYEMBED_LDFLAGS
  226. """
  227. features = Utils.to_list(features)
  228. if not ('PYTHON_LDFLAGS' in self.environ or 'PYTHON_PYEXT_LDFLAGS' in self.environ or 'PYTHON_PYEMBED_LDFLAGS' in self.environ):
  229. return False
  230. for x in 'PYTHON_VERSION PYTAG pyext_PATTERN'.split():
  231. if not x in self.environ:
  232. self.fatal('Please set %s in the os environment' % x)
  233. else:
  234. self.env[x] = self.environ[x]
  235. xx = self.env.CXX_NAME and 'cxx' or 'c'
  236. if 'pyext' in features:
  237. flags = self.environ.get('PYTHON_PYEXT_LDFLAGS', self.environ.get('PYTHON_LDFLAGS'))
  238. if flags is None:
  239. self.fatal('No flags provided through PYTHON_PYEXT_LDFLAGS as required')
  240. else:
  241. self.parse_flags(flags, 'PYEXT')
  242. self.test_pyext(xx)
  243. if 'pyembed' in features:
  244. flags = self.environ.get('PYTHON_PYEMBED_LDFLAGS', self.environ.get('PYTHON_LDFLAGS'))
  245. if flags is None:
  246. self.fatal('No flags provided through PYTHON_PYEMBED_LDFLAGS as required')
  247. else:
  248. self.parse_flags(flags, 'PYEMBED')
  249. self.test_pyembed(xx)
  250. return True
  251. @conf
  252. def check_python_headers(conf, features='pyembed pyext'):
  253. """
  254. Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
  255. On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:
  256. * PYEXT: for compiling python extensions
  257. * PYEMBED: for embedding a python interpreter
  258. """
  259. features = Utils.to_list(features)
  260. assert ('pyembed' in features) or ('pyext' in features), "check_python_headers features must include 'pyembed' and/or 'pyext'"
  261. env = conf.env
  262. if not env.CC_NAME and not env.CXX_NAME:
  263. conf.fatal('load a compiler first (gcc, g++, ..)')
  264. # bypass all the code below for cross-compilation
  265. if conf.python_cross_compile(features):
  266. return
  267. if not env.PYTHON_VERSION:
  268. conf.check_python_version()
  269. pybin = env.PYTHON
  270. if not pybin:
  271. conf.fatal('Could not find the python executable')
  272. # so we actually do all this for compatibility reasons and for obtaining pyext_PATTERN below
  273. v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split()
  274. try:
  275. lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
  276. except RuntimeError:
  277. conf.fatal("Python development headers not found (-v for details).")
  278. vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
  279. conf.to_log("Configuration returned from %r:\n%s\n" % (pybin, '\n'.join(vals)))
  280. dct = dict(zip(v, lst))
  281. x = 'MACOSX_DEPLOYMENT_TARGET'
  282. if dct[x]:
  283. env[x] = conf.environ[x] = dct[x]
  284. env.pyext_PATTERN = '%s' + dct['SO'] # not a mistake
  285. # Try to get pythonX.Y-config
  286. num = '.'.join(env.PYTHON_VERSION.split('.')[:2])
  287. conf.find_program([''.join(pybin) + '-config', 'python%s-config' % num, 'python-config-%s' % num, 'python%sm-config' % num], var='PYTHON_CONFIG', msg="python-config", mandatory=False)
  288. if env.PYTHON_CONFIG:
  289. # python2.6-config requires 3 runs
  290. all_flags = [['--cflags', '--libs', '--ldflags']]
  291. if sys.hexversion < 0x2070000:
  292. all_flags = [[k] for k in all_flags[0]]
  293. xx = env.CXX_NAME and 'cxx' or 'c'
  294. if 'pyembed' in features:
  295. for flags in all_flags:
  296. conf.check_cfg(msg='Asking python-config for pyembed %r flags' % ' '.join(flags), path=env.PYTHON_CONFIG, package='', uselib_store='PYEMBED', args=flags)
  297. try:
  298. conf.test_pyembed(xx)
  299. except conf.errors.ConfigurationError:
  300. # python bug 7352
  301. if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
  302. env.append_unique('LIBPATH_PYEMBED', [dct['LIBDIR']])
  303. conf.test_pyembed(xx)
  304. else:
  305. raise
  306. if 'pyext' in features:
  307. for flags in all_flags:
  308. conf.check_cfg(msg='Asking python-config for pyext %r flags' % ' '.join(flags), path=env.PYTHON_CONFIG, package='', uselib_store='PYEXT', args=flags)
  309. try:
  310. conf.test_pyext(xx)
  311. except conf.errors.ConfigurationError:
  312. # python bug 7352
  313. if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
  314. env.append_unique('LIBPATH_PYEXT', [dct['LIBDIR']])
  315. conf.test_pyext(xx)
  316. else:
  317. raise
  318. conf.define('HAVE_PYTHON_H', 1)
  319. return
  320. # No python-config, do something else on windows systems
  321. all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
  322. conf.parse_flags(all_flags, 'PYEMBED')
  323. all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
  324. conf.parse_flags(all_flags, 'PYEXT')
  325. result = None
  326. if not dct["LDVERSION"]:
  327. dct["LDVERSION"] = env.PYTHON_VERSION
  328. # further simplification will be complicated
  329. for name in ('python' + dct['LDVERSION'], 'python' + env.PYTHON_VERSION + 'm', 'python' + env.PYTHON_VERSION.replace('.', '')):
  330. # LIBPATH_PYEMBED is already set; see if it works.
  331. if not result and env.LIBPATH_PYEMBED:
  332. path = env.LIBPATH_PYEMBED
  333. conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
  334. result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBPATH_PYEMBED' % name)
  335. if not result and dct['LIBDIR']:
  336. path = [dct['LIBDIR']]
  337. conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
  338. result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBDIR' % name)
  339. if not result and dct['LIBPL']:
  340. path = [dct['LIBPL']]
  341. conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
  342. result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in python_LIBPL' % name)
  343. if not result:
  344. path = [os.path.join(dct['prefix'], "libs")]
  345. conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
  346. result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in $prefix/libs' % name)
  347. if result:
  348. break # do not forget to set LIBPATH_PYEMBED
  349. if result:
  350. env.LIBPATH_PYEMBED = path
  351. env.append_value('LIB_PYEMBED', [name])
  352. else:
  353. conf.to_log("\n\n### LIB NOT FOUND\n")
  354. # under certain conditions, python extensions must link to
  355. # python libraries, not just python embedding programs.
  356. if Utils.is_win32 or dct['Py_ENABLE_SHARED']:
  357. env.LIBPATH_PYEXT = env.LIBPATH_PYEMBED
  358. env.LIB_PYEXT = env.LIB_PYEMBED
  359. conf.to_log("Include path for Python extensions (found via distutils module): %r\n" % (dct['INCLUDEPY'],))
  360. env.INCLUDES_PYEXT = [dct['INCLUDEPY']]
  361. env.INCLUDES_PYEMBED = [dct['INCLUDEPY']]
  362. # Code using the Python API needs to be compiled with -fno-strict-aliasing
  363. if env.CC_NAME == 'gcc':
  364. env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
  365. env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
  366. if env.CXX_NAME == 'gcc':
  367. env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
  368. env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])
  369. if env.CC_NAME == "msvc":
  370. from distutils.msvccompiler import MSVCCompiler
  371. dist_compiler = MSVCCompiler()
  372. dist_compiler.initialize()
  373. env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
  374. env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
  375. env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)
  376. # See if it compiles
  377. conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H', uselib='PYEMBED', fragment=FRAG, errmsg='Distutils not installed? Broken python installation? Get python-config now!')
  378. @conf
  379. def check_python_version(conf, minver=None):
  380. """
  381. Check if the python interpreter is found matching a given minimum version.
  382. minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver.
  383. If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR' (eg. '2.4')
  384. of the actual python version found, and PYTHONDIR and PYTHONARCHDIR
  385. are defined, pointing to the site-packages directories appropriate for
  386. this python version, where modules/packages/extensions should be
  387. installed.
  388. :param minver: minimum version
  389. :type minver: tuple of int
  390. """
  391. assert minver is None or isinstance(minver, tuple)
  392. pybin = conf.env.PYTHON
  393. if not pybin:
  394. conf.fatal('could not find the python executable')
  395. # Get python version string
  396. cmd = pybin + ['-c', 'import sys\nfor x in sys.version_info: print(str(x))']
  397. Logs.debug('python: Running python command %r', cmd)
  398. lines = conf.cmd_and_log(cmd).split()
  399. assert len(lines) == 5, "found %r lines, expected 5: %r" % (len(lines), lines)
  400. pyver_tuple = (int(lines[0]), int(lines[1]), int(lines[2]), lines[3], int(lines[4]))
  401. # Compare python version with the minimum required
  402. result = (minver is None) or (pyver_tuple >= minver)
  403. if result:
  404. # define useful environment variables
  405. pyver = '.'.join([str(x) for x in pyver_tuple[:2]])
  406. conf.env.PYTHON_VERSION = pyver
  407. if 'PYTHONDIR' in conf.env:
  408. # Check if --pythondir was specified
  409. pydir = conf.env.PYTHONDIR
  410. elif 'PYTHONDIR' in conf.environ:
  411. # Check environment for PYTHONDIR
  412. pydir = conf.environ['PYTHONDIR']
  413. else:
  414. # Finally, try to guess
  415. if Utils.is_win32:
  416. (python_LIBDEST, pydir) = conf.get_python_variables(
  417. ["get_config_var('LIBDEST') or ''",
  418. "get_python_lib(standard_lib=0) or ''"])
  419. else:
  420. python_LIBDEST = None
  421. (pydir,) = conf.get_python_variables( ["get_python_lib(standard_lib=0, prefix=%r) or ''" % conf.env.PREFIX])
  422. if python_LIBDEST is None:
  423. if conf.env.LIBDIR:
  424. python_LIBDEST = os.path.join(conf.env.LIBDIR, 'python' + pyver)
  425. else:
  426. python_LIBDEST = os.path.join(conf.env.PREFIX, 'lib', 'python' + pyver)
  427. if 'PYTHONARCHDIR' in conf.env:
  428. # Check if --pythonarchdir was specified
  429. pyarchdir = conf.env.PYTHONARCHDIR
  430. elif 'PYTHONARCHDIR' in conf.environ:
  431. # Check environment for PYTHONDIR
  432. pyarchdir = conf.environ['PYTHONARCHDIR']
  433. else:
  434. # Finally, try to guess
  435. (pyarchdir, ) = conf.get_python_variables( ["get_python_lib(plat_specific=1, standard_lib=0, prefix=%r) or ''" % conf.env.PREFIX])
  436. if not pyarchdir:
  437. pyarchdir = pydir
  438. if hasattr(conf, 'define'): # conf.define is added by the C tool, so may not exist
  439. conf.define('PYTHONDIR', pydir)
  440. conf.define('PYTHONARCHDIR', pyarchdir)
  441. conf.env.PYTHONDIR = pydir
  442. conf.env.PYTHONARCHDIR = pyarchdir
  443. # Feedback
  444. pyver_full = '.'.join(map(str, pyver_tuple[:3]))
  445. if minver is None:
  446. conf.msg('Checking for python version', pyver_full)
  447. else:
  448. minver_str = '.'.join(map(str, minver))
  449. conf.msg('Checking for python version >= %s' % (minver_str,), pyver_full, color=result and 'GREEN' or 'YELLOW')
  450. if not result:
  451. conf.fatal('The python version is too old, expecting %r' % (minver,))
  452. PYTHON_MODULE_TEMPLATE = '''
  453. import %s as current_module
  454. version = getattr(current_module, '__version__', None)
  455. if version is not None:
  456. print(str(version))
  457. else:
  458. print('unknown version')
  459. '''
  460. @conf
  461. def check_python_module(conf, module_name, condition=''):
  462. """
  463. Check if the selected python interpreter can import the given python module::
  464. def configure(conf):
  465. conf.check_python_module('pygccxml')
  466. conf.check_python_module('re', condition="ver > num(2, 0, 4) and ver <= num(3, 0, 0)")
  467. :param module_name: module
  468. :type module_name: string
  469. """
  470. msg = "Checking for python module %r" % module_name
  471. if condition:
  472. msg = '%s (%s)' % (msg, condition)
  473. conf.start_msg(msg)
  474. try:
  475. ret = conf.cmd_and_log(conf.env.PYTHON + ['-c', PYTHON_MODULE_TEMPLATE % module_name])
  476. except Errors.WafError:
  477. conf.end_msg(False)
  478. conf.fatal('Could not find the python module %r' % module_name)
  479. ret = ret.strip()
  480. if condition:
  481. conf.end_msg(ret)
  482. if ret == 'unknown version':
  483. conf.fatal('Could not check the %s version' % module_name)
  484. from distutils.version import LooseVersion
  485. def num(*k):
  486. if isinstance(k[0], int):
  487. return LooseVersion('.'.join([str(x) for x in k]))
  488. else:
  489. return LooseVersion(k[0])
  490. d = {'num': num, 'ver': LooseVersion(ret)}
  491. ev = eval(condition, {}, d)
  492. if not ev:
  493. conf.fatal('The %s version does not satisfy the requirements' % module_name)
  494. else:
  495. if ret == 'unknown version':
  496. conf.end_msg(True)
  497. else:
  498. conf.end_msg(ret)
  499. def configure(conf):
  500. """
  501. Detect the python interpreter
  502. """
  503. v = conf.env
  504. if getattr(Options.options, 'pythondir', None):
  505. v.PYTHONDIR = Options.options.pythondir
  506. if getattr(Options.options, 'pythonarchdir', None):
  507. v.PYTHONARCHDIR = Options.options.pythonarchdir
  508. if getattr(Options.options, 'nopycache', None):
  509. v.NOPYCACHE=Options.options.nopycache
  510. if not v.PYTHON:
  511. v.PYTHON = [getattr(Options.options, 'python', None) or sys.executable]
  512. v.PYTHON = Utils.to_list(v.PYTHON)
  513. conf.find_program('python', var='PYTHON')
  514. v.PYFLAGS = ''
  515. v.PYFLAGS_OPT = '-O'
  516. v.PYC = getattr(Options.options, 'pyc', 1)
  517. v.PYO = getattr(Options.options, 'pyo', 1)
  518. try:
  519. v.PYTAG = conf.cmd_and_log(conf.env.PYTHON + ['-c', "import imp;print(imp.get_tag())"]).strip()
  520. except Errors.WafError:
  521. pass
  522. def options(opt):
  523. """
  524. Add python-specific options
  525. """
  526. pyopt=opt.add_option_group("Python Options")
  527. pyopt.add_option('--nopyc', dest = 'pyc', action='store_false', default=1,
  528. help = 'Do not install bytecode compiled .pyc files (configuration) [Default:install]')
  529. pyopt.add_option('--nopyo', dest='pyo', action='store_false', default=1,
  530. help='Do not install optimised compiled .pyo files (configuration) [Default:install]')
  531. pyopt.add_option('--nopycache',dest='nopycache', action='store_true',
  532. help='Do not use __pycache__ directory to install objects [Default:auto]')
  533. pyopt.add_option('--python', dest="python",
  534. help='python binary to be used [Default: %s]' % sys.executable)
  535. pyopt.add_option('--pythondir', dest='pythondir',
  536. help='Installation path for python modules (py, platform-independent .py and .pyc files)')
  537. pyopt.add_option('--pythonarchdir', dest='pythonarchdir',
  538. help='Installation path for python extension (pyext, platform-dependent .so or .dylib files)')