Beispiel #1
0
def SAMBA_CHECK_PYTHON(conf, version=(3, 6, 0)):

    if conf.env.disable_python:
        version = (2, 6, 0)

    if conf.env.enable_fuzzing:
        version = (3, 5, 0)

    # enable tool to build python extensions
    if conf.env.HAVE_PYTHON_H:
        conf.check_python_version(version)
        return

    interpreters = []

    conf.find_program('python3',
                      var='PYTHON',
                      mandatory=not conf.env.disable_python)
    conf.load('python')
    path_python = conf.find_program('python3')

    conf.env.PYTHON_SPECIFIED = (conf.env.PYTHON != path_python)
    conf.check_python_version(version)

    interpreters.append(conf.env['PYTHON'])
    conf.env.python_interpreters = interpreters
Beispiel #2
0
def check_python_headers(conf):
    """
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""

    # FIXME rewrite

    if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')

    if not conf.env['PYTHON_VERSION']:
        conf.check_python_version()

    env = conf.env
    pybin = env.PYTHON
    if not pybin:
        conf.fatal('could not find the python executable')

    v = 'INCLUDEPY SO LDFLAGS MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" %
                (pybin, '\n'.join(vals)))

    dct = dict(list(zip(v, lst)))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]

    env['pyext_PATTERN'] = '%s' + dct['SO']  # not a mistake

    if Options.options.use_distutils_flags:
        all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
        conf.parse_flags(all_flags, 'PYEXT')

    env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
Beispiel #3
0
def check_python_headers(conf):
	"""
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""

	# FIXME rewrite

	if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')

	if not conf.env['PYTHON_VERSION']:
		conf.check_python_version()

	env = conf.env
	pybin = env.PYTHON
	if not pybin:
		conf.fatal('could not find the python executable')

	v = 'INCLUDEPY SO LDFLAGS MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
	try:
		lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")

	vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
	conf.to_log("Configuration returned from %r:\n%r\n" % (pybin, '\n'.join(vals)))

	dct = dict(zip(v, lst))
	x = 'MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x] = conf.environ[x] = dct[x]

	env['pyext_PATTERN'] = '%s' + dct['SO'] # not a mistake

	if Options.options.use_distutils_flags:
		all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
		conf.parse_flags(all_flags, 'PYEXT')

	env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
def configure(conf):
    conf.env.PYTHON = sys.executable
    conf.load('python compiler_c')
    conf.check_python_version((2,7))
    conf.check_python_module('numpy','ver >= num(1,5)')

    for k,v in conf.environ.items():
        if any(k.startswith(p) for p in ['LIB','LIBPATH','LINKFLAGS','CFLAGS','FCFLAGS']): 
            conf.env.append_value(k, to_list(conf.environ[k]))

    if conf.options.PLUGIN is not None:
        success, fail = [conf.srcnode.find_node("cosmoslik_plugins").make_node(conf.options.PLUGIN)], []
        conf.recurse(success[0].abspath())
    else:
        if conf.options.EXCLUDE is not None:
            exclude = [conf.srcnode.find_node("cosmoslik_plugins/").find_node(e) for e in conf.options.EXCLUDE]
        else:
            exclude = []
        success, fail = recurse(conf,keep_going=True,exclude=exclude)
        
    if len(success)>0:
        sys.stdout.write('\033[1m')
        print "The following plugins are ready to build:"
        sys.stdout.write('\033[92m')
        for f in success: print "  "+f.path_from(conf.srcnode.find_node("cosmoslik_plugins/"))
        sys.stdout.write('\033[0m')
    if len(fail)>0:
        sys.stdout.write('\033[1m')
        print "The following plugins can't be built (ignore if not needed):"
        sys.stdout.write('\033[93m')
        for f in fail: print "  "+f.path_from(conf.srcnode.find_node("cosmoslik_plugins/"))
        sys.stdout.write('\033[0m')
        print "Run './waf configure --plugin PLUGIN' to see why a given plugin can't build."
        print "where PLUGIN is exactly as it appears above."

    conf.env.configured_plugins = [f.path_from(conf.srcnode) for f in success]

    if conf.options.inplace: 
        conf.env.PYTHONDIR = '.'
        conf.env.INPLACE = True
Beispiel #5
0
def SAMBA_CHECK_PYTHON(conf, mandatory=True, version=(2, 6, 0)):
    # enable tool to build python extensions
    if conf.env.HAVE_PYTHON_H:
        conf.check_python_version(version)
        return

    interpreters = []

    if conf.env['EXTRA_PYTHON']:
        conf.all_envs['extrapython'] = conf.env.derive()
        conf.setenv('extrapython')
        conf.env['PYTHON'] = conf.env['EXTRA_PYTHON']
        conf.env['IS_EXTRA_PYTHON'] = 'yes'
        conf.find_program('python', var='PYTHON', mandatory=True)
        conf.load('python')
        try:
            conf.check_python_version(version)
        except Exception:
            Logs.warn('extra-python needs to be Python %s.%s.%s or later' %
                      (version[0], version[1], version[2]))
            raise
        interpreters.append(conf.env['PYTHON'])
        conf.setenv('default')

    conf.find_program('python3', var='PYTHON', mandatory=mandatory)
    conf.load('python')
    path_python = conf.find_program('python3')

    conf.env.PYTHON_SPECIFIED = (conf.env.PYTHON != path_python)
    conf.check_python_version(version)

    interpreters.append(conf.env['PYTHON'])
    conf.env.python_interpreters = interpreters
Beispiel #6
0
def check_python_headers(conf):
	env=conf.env
	if not env['CC_NAME']and not env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')
	if not env['PYTHON_VERSION']:
		conf.check_python_version()
	pybin=conf.env.PYTHON
	if not pybin:
		conf.fatal('Could not find the python executable')
	v='prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split()
	try:
		lst=conf.get_python_variables(["get_config_var('%s') or ''"%x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")
	vals=['%s = %r'%(x,y)for(x,y)in zip(v,lst)]
	conf.to_log("Configuration returned from %r:\n%r\n"%(pybin,'\n'.join(vals)))
	dct=dict(zip(v,lst))
	x='MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x]=conf.environ[x]=dct[x]
	if not env.pyext_PATTERN:
		if dct['SO']:
			env.pyext_PATTERN='%s'+dct['SO']
		else:
			env.pyext_PATTERN=(conf.env.cshlib_PATTERN or conf.env.cxxshlib_PATTERN).lstrip('lib')
	num='.'.join(env['PYTHON_VERSION'].split('.')[:2])
	conf.find_program([''.join(pybin)+'-config','python%s-config'%num,'python-config-%s'%num,'python%sm-config'%num],var='PYTHON_CONFIG',msg="python-config")
	all_flags=[['--cflags','--libs','--ldflags']]
	if sys.hexversion<0x2060000:
		all_flags=[[x]for x in all_flags[0]]
	xx=conf.env.CXX_NAME and'cxx'or'c'
	for flags in all_flags:
		conf.check_cfg(msg='Asking python-config for pyembed %r flags'%' '.join(flags),path=conf.env.PYTHON_CONFIG,package='',uselib_store='PYEMBED',args=flags)
	conf.check(header_name='Python.h',define_name='HAVE_PYEMBED',msg='Getting pyembed flags from python-config',fragment=FRAG,errmsg='Could not build a python embedded interpreter',features='%s %sprogram pyembed'%(xx,xx))
	for flags in all_flags:
		conf.check_cfg(msg='Asking python-config for pyext %r flags'%' '.join(flags),path=conf.env.PYTHON_CONFIG,package='',uselib_store='PYEXT',args=flags)
	conf.check(header_name='Python.h',define_name='HAVE_PYEXT',msg='Getting pyext flags from python-config',features='%s %sshlib pyext'%(xx,xx),fragment=FRAG,errmsg='Could not build python extensions')
	conf.define('HAVE_PYTHON_H',1)
Beispiel #7
0
def check_python_headers(conf):
    env = conf.env
    if not env['CC_NAME'] and not env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')
    if not env['PYTHON_VERSION']:
        conf.check_python_version()
    pybin = conf.env.PYTHON
    if not pybin:
        conf.fatal('Could not find the python executable')
    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")
    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" %
                (pybin, '\n'.join(vals)))
    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]
    env['pyext_PATTERN'] = '%s' + dct['SO']
    all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEMBED')
    all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEXT')
    result = None
    for name in ('python' + env['PYTHON_VERSION'],
                 'python' + env['PYTHON_VERSION'].replace('.', '')):
        if not result and env['LIBPATH_PYEMBED']:
            path = env['LIBPATH_PYEMBED']
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib='PYEMBED',
                libpath=path,
                mandatory=False,
                msg='Checking for library %s in LIBPATH_PYEMBED' % name)
        if not result and dct['LIBDIR']:
            path = [dct['LIBDIR']]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in LIBDIR' % name)
        if not result and dct['LIBPL']:
            path = [dct['LIBPL']]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in python_LIBPL' %
                                name)
        if not result:
            path = [os.path.join(dct['prefix'], "libs")]
            conf.to_log(
                "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in $prefix/libs' %
                                name)
        if result:
            break
    if result:
        env['LIBPATH_PYEMBED'] = path
        env.append_value('LIB_PYEMBED', [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")
    if (Utils.is_win32 or sys.platform.startswith('os2')
            or dct['Py_ENABLE_SHARED']):
        env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
        env['LIB_PYEXT'] = env['LIB_PYEMBED']
    num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
    conf.find_program([
        ''.join(pybin) + '-config',
        'python%s-config' % num,
        'python-config-%s' % num,
        'python%sm-config' % num
    ],
                      var='PYTHON_CONFIG',
                      mandatory=False)
    includes = []
    if conf.env.PYTHON_CONFIG:
        for incstr in conf.cmd_and_log([conf.env.PYTHON_CONFIG,
                                        '--includes']).strip().split():
            if (incstr.startswith('-I') or incstr.startswith('/I')):
                incstr = incstr[2:]
            if incstr not in includes:
                includes.append(incstr)
        conf.to_log(
            "Include path for Python extensions (found via python-config --includes): %r\n"
            % (includes, ))
        env['INCLUDES_PYEXT'] = includes
        env['INCLUDES_PYEMBED'] = includes
    else:
        conf.to_log("Include path for Python extensions "
                    "(found via distutils module): %r\n" %
                    (dct['INCLUDEPY'], ))
        env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
        env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]
    if env['CC_NAME'] == 'gcc':
        env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env['CXX_NAME'] == 'gcc':
        env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler
        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)
    try:
        conf.check(header_name='Python.h',
                   define_name='HAVE_PYTHON_H',
                   uselib='PYEMBED',
                   fragment=FRAG,
                   errmsg=':-(')
    except conf.errors.ConfigurationError:
        xx = conf.env.CXX_NAME and 'cxx' or 'c'
        conf.check_cfg(msg='Asking python-config for the flags (pyembed)',
                       path=conf.env.PYTHON_CONFIG,
                       package='',
                       uselib_store='PYEMBED',
                       args=['--cflags', '--libs', '--ldflags'])
        conf.check(header_name='Python.h',
                   define_name='HAVE_PYTHON_H',
                   msg='Getting pyembed flags from python-config',
                   fragment=FRAG,
                   errmsg='Could not build a python embedded interpreter',
                   features='%s %sprogram pyembed' % (xx, xx))
        conf.check_cfg(msg='Asking python-config for the flags (pyext)',
                       path=conf.env.PYTHON_CONFIG,
                       package='',
                       uselib_store='PYEXT',
                       args=['--cflags', '--libs', '--ldflags'])
        conf.check(header_name='Python.h',
                   define_name='HAVE_PYTHON_H',
                   msg='Getting pyext flags from python-config',
                   features='%s %sshlib pyext' % (xx, xx),
                   fragment=FRAG,
                   errmsg='Could not build python extensions')
Beispiel #8
0
def check_python_headers(conf):
    """
    Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
    On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

    * PYEXT: for compiling python extensions
    * PYEMBED: for embedding a python interpreter
    """

    # FIXME rewrite

    if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')

    if not conf.env['PYTHON_VERSION']:
        conf.check_python_version()

    env = conf.env
    pybin = conf.env.PYTHON
    if not pybin:
        conf.fatal('could not find the python executable')

    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v],
            ['from distutils.sysconfig import get_config_var'])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" %
                (pybin, '\n'.join(vals)))

    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]

    env['pyext_PATTERN'] = '%s' + dct['SO']  # not a mistake

    # Check for python libraries for embedding

    all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEMBED')
    conf.parse_flags(all_flags, 'PYEXT')

    result = None
    #name = 'python' + env['PYTHON_VERSION']

    # TODO simplify this
    for name in ('python' + env['PYTHON_VERSION'],
                 'python' + env['PYTHON_VERSION'].replace('.', '')):

        if Utils.is_win32 and name == "python2.7":
            name = "python27"
            print "walif/tools/python.py: python hack for windows"

        #name.replace('.', '')

        # LIBPATH_PYEMBED is already set; see if it works.
        if not result and env['LIBPATH_PYEMBED']:
            path = env['LIBPATH_PYEMBED']
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib='PYEMBED',
                libpath=path,
                mandatory=False,
                msg='Checking for library %s in LIBPATH_PYEMBED' % name)

        if not result and dct['LIBDIR']:
            path = [dct['LIBDIR']]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in LIBDIR' % name)

        if not result and dct['LIBPL']:
            path = [dct['LIBPL']]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in python_LIBPL' %
                                name)

        if not result:
            path = [os.path.join(dct['prefix'], "libs")]
            conf.to_log(
                "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in $prefix/libs' %
                                name)

        if result:
            break  # do not forget to set LIBPATH_PYEMBED

    if result:
        env['LIBPATH_PYEMBED'] = path
        env.append_value('LIB_PYEMBED', [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")

    # under certain conditions, python extensions must link to
    # python libraries, not just python embedding programs.
    if (Utils.is_win32 or sys.platform.startswith('os2')
            or sys.platform == 'darwin' or dct['Py_ENABLE_SHARED']):
        env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
        env['LIB_PYEXT'] = env['LIB_PYEMBED']

    # We check that pythonX.Y-config exists, and if it exists we
    # use it to get only the includes, else fall back to distutils.
    num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
    conf.find_program([
        'python%s-config' % num,
        'python-config-%s' % num,
        'python%sm-config' % num
    ],
                      var='PYTHON_CONFIG',
                      mandatory=False)

    includes = []
    if conf.env.PYTHON_CONFIG:
        for incstr in conf.cmd_and_log([conf.env.PYTHON_CONFIG,
                                        '--includes']).strip().split():
            # strip the -I or /I
            if (incstr.startswith('-I') or incstr.startswith('/I')):
                incstr = incstr[2:]
            # append include path, unless already given
            if incstr not in includes:
                includes.append(incstr)
        conf.to_log("Include path for Python extensions "
                    "(found via python-config --includes): %r\n" %
                    (includes, ))
        env['INCLUDES_PYEXT'] = includes
        env['INCLUDES_PYEMBED'] = includes
    else:
        conf.to_log("Include path for Python extensions "
                    "(found via distutils module): %r\n" %
                    (dct['INCLUDEPY'], ))
        env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
        env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]

    # Code using the Python API needs to be compiled with -fno-strict-aliasing
    if env['CC_NAME'] == 'gcc':
        env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env['CXX_NAME'] == 'gcc':
        env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

    # See if it compiles
    try:
        conf.check(header_name='Python.h',
                   define_name='HAVE_PYTHON_H',
                   uselib='PYEMBED',
                   fragment=FRAG,
                   errmsg='Could not find the python development headers')
    except conf.errors.ConfigurationError:
        # python3.2, oh yeah
        conf.check_cfg(path=conf.env.PYTHON_CONFIG,
                       package='',
                       uselib_store='PYEMBED',
                       args=['--cflags', '--libs'])
        conf.check(
            header_name='Python.h',
            define_name='HAVE_PYTHON_H',
            msg='Getting the python flags from python-config',
            uselib='PYEMBED',
            fragment=FRAG,
            errmsg='Could not find the python development headers elsewhere')
def check_python_headers(conf, features="pyembed pyext"):
    """
    Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
    On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

    * PYEXT: for compiling python extensions
    * PYEMBED: for embedding a python interpreter
    """
    features = Utils.to_list(features)
    assert ("pyembed" in features) or (
        "pyext" in features
    ), "check_python_headers features must include 'pyembed' and/or 'pyext'"
    env = conf.env
    if not env.CC_NAME and not env.CXX_NAME:
        conf.fatal("load a compiler first (gcc, g++, ..)")

    # bypass all the code below for cross-compilation
    if conf.python_cross_compile(features):
        return

    if not env.PYTHON_VERSION:
        conf.check_python_version()

    pybin = env.PYTHON
    if not pybin:
        conf.fatal("Could not find the python executable")

    # so we actually do all this for compatibility reasons and for obtaining pyext_PATTERN below
    v = "prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION".split()
    try:
        lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = [f"{x} = {y!r}" for (x, y) in zip(v, lst)]
    conf.to_log(
        "Configuration returned from {!r}:\n{}\n".format(pybin, "\n".join(vals))
    )

    dct = dict(zip(v, lst))
    x = "MACOSX_DEPLOYMENT_TARGET"
    if dct[x]:
        env[x] = conf.environ[x] = dct[x]
    env.pyext_PATTERN = "%s" + dct["SO"]  # not a mistake

    # Try to get pythonX.Y-config
    num = ".".join(env.PYTHON_VERSION.split(".")[:2])
    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,
    )

    if env.PYTHON_CONFIG:
        # python2.6-config requires 3 runs
        all_flags = [["--cflags", "--libs", "--ldflags"]]
        if sys.hexversion < 0x2070000:
            all_flags = [[k] for k in all_flags[0]]

        xx = env.CXX_NAME and "cxx" or "c"

        if "pyembed" in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg="Asking python-config for pyembed %r flags" % " ".join(flags),
                    path=env.PYTHON_CONFIG,
                    package="",
                    uselib_store="PYEMBED",
                    args=flags,
                )

            try:
                conf.test_pyembed(xx)
            except conf.errors.ConfigurationError:
                # python bug 7352
                if dct["Py_ENABLE_SHARED"] and dct["LIBDIR"]:
                    env.append_unique("LIBPATH_PYEMBED", [dct["LIBDIR"]])
                    conf.test_pyembed(xx)
                else:
                    raise

        if "pyext" in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg="Asking python-config for pyext %r flags" % " ".join(flags),
                    path=env.PYTHON_CONFIG,
                    package="",
                    uselib_store="PYEXT",
                    args=flags,
                )

            try:
                conf.test_pyext(xx)
            except conf.errors.ConfigurationError:
                # python bug 7352
                if dct["Py_ENABLE_SHARED"] and dct["LIBDIR"]:
                    env.append_unique("LIBPATH_PYEXT", [dct["LIBDIR"]])
                    conf.test_pyext(xx)
                else:
                    raise

        conf.define("HAVE_PYTHON_H", 1)
        return

    # No python-config, do something else on windows systems
    all_flags = dct["LDFLAGS"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEMBED")

    all_flags = dct["LDFLAGS"] + " " + dct["LDSHARED"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEXT")

    result = None
    if not dct["LDVERSION"]:
        dct["LDVERSION"] = env.PYTHON_VERSION

    # further simplification will be complicated
    for name in (
        "python" + dct["LDVERSION"],
        "python" + env.PYTHON_VERSION + "m",
        "python" + env.PYTHON_VERSION.replace(".", ""),
    ):

        # LIBPATH_PYEMBED is already set; see if it works.
        if not result and env.LIBPATH_PYEMBED:
            path = env.LIBPATH_PYEMBED
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBPATH_PYEMBED" % name,
            )

        if not result and dct["LIBDIR"]:
            path = [dct["LIBDIR"]]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBDIR" % name,
            )

        if not result and dct["LIBPL"]:
            path = [dct["LIBPL"]]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in python_LIBPL" % name,
            )

        if not result:
            path = [os.path.join(dct["prefix"], "libs")]
            conf.to_log(
                "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
            )
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in $prefix/libs" % name,
            )

        if result:
            break  # do not forget to set LIBPATH_PYEMBED

    if result:
        env.LIBPATH_PYEMBED = path
        env.append_value("LIB_PYEMBED", [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")

    # under certain conditions, python extensions must link to
    # python libraries, not just python embedding programs.
    if Utils.is_win32 or dct["Py_ENABLE_SHARED"]:
        env.LIBPATH_PYEXT = env.LIBPATH_PYEMBED
        env.LIB_PYEXT = env.LIB_PYEMBED

    conf.to_log(
        "Include path for Python extensions (found via distutils module): {!r}\n".format(
            dct["INCLUDEPY"]
        )
    )
    env.INCLUDES_PYEXT = [dct["INCLUDEPY"]]
    env.INCLUDES_PYEMBED = [dct["INCLUDEPY"]]

    # Code using the Python API needs to be compiled with -fno-strict-aliasing
    if env.CC_NAME == "gcc":
        env.append_value("CFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CFLAGS_PYEXT", ["-fno-strict-aliasing"])
    if env.CXX_NAME == "gcc":
        env.append_value("CXXFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CXXFLAGS_PYEXT", ["-fno-strict-aliasing"])

    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler

        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value("CFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("CXXFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("LINKFLAGS_PYEXT", dist_compiler.ldflags_shared)

    # See if it compiles
    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!",
    )
Beispiel #10
0
def check_python_headers(conf):
	env=conf.env
	if not env['CC_NAME']and not env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')
	if not env['PYTHON_VERSION']:
		conf.check_python_version()
	pybin=env.PYTHON
	if not pybin:
		conf.fatal('Could not find the python executable')
	v='prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split()
	try:
		lst=conf.get_python_variables(["get_config_var('%s') or ''"%x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")
	vals=['%s = %r'%(x,y)for(x,y)in zip(v,lst)]
	conf.to_log("Configuration returned from %r:\n%r\n"%(pybin,'\n'.join(vals)))
	dct=dict(zip(v,lst))
	x='MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		env[x]=conf.environ[x]=dct[x]
	env['pyext_PATTERN']='%s'+dct['SO']
	num='.'.join(env['PYTHON_VERSION'].split('.')[:2])
	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)
	if env.PYTHON_CONFIG:
		all_flags=[['--cflags','--libs','--ldflags']]
		if sys.hexversion<0x2060000:
			all_flags=[[k]for k in all_flags[0]]
		xx=env.CXX_NAME and'cxx'or'c'
		for flags in all_flags:
			conf.check_cfg(msg='Asking python-config for pyembed %r flags'%' '.join(flags),path=env.PYTHON_CONFIG,package='',uselib_store='PYEMBED',args=flags)
		conf.check(header_name='Python.h',define_name='HAVE_PYEMBED',msg='Getting pyembed flags from python-config',fragment=FRAG,errmsg='Could not build a python embedded interpreter',features='%s %sprogram pyembed'%(xx,xx))
		for flags in all_flags:
			conf.check_cfg(msg='Asking python-config for pyext %r flags'%' '.join(flags),path=env.PYTHON_CONFIG,package='',uselib_store='PYEXT',args=flags)
		conf.check(header_name='Python.h',define_name='HAVE_PYEXT',msg='Getting pyext flags from python-config',features='%s %sshlib pyext'%(xx,xx),fragment=FRAG,errmsg='Could not build python extensions')
		conf.define('HAVE_PYTHON_H',1)
		return
	all_flags=dct['LDFLAGS']+' '+dct['CFLAGS']
	conf.parse_flags(all_flags,'PYEMBED')
	all_flags=dct['LDFLAGS']+' '+dct['LDSHARED']+' '+dct['CFLAGS']
	conf.parse_flags(all_flags,'PYEXT')
	result=None
	if not dct["LDVERSION"]:
		dct["LDVERSION"]=env['PYTHON_VERSION']
	for name in('python'+dct['LDVERSION'],'python'+env['PYTHON_VERSION']+'m','python'+env['PYTHON_VERSION'].replace('.','')):
		if not result and env['LIBPATH_PYEMBED']:
			path=env['LIBPATH_PYEMBED']
			conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n"%path)
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in LIBPATH_PYEMBED'%name)
		if not result and dct['LIBDIR']:
			path=[dct['LIBDIR']]
			conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n"%path)
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in LIBDIR'%name)
		if not result and dct['LIBPL']:
			path=[dct['LIBPL']]
			conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in python_LIBPL'%name)
		if not result:
			path=[os.path.join(dct['prefix'],"libs")]
			conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in $prefix/libs'%name)
		if result:
			break
	if result:
		env['LIBPATH_PYEMBED']=path
		env.append_value('LIB_PYEMBED',[name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")
	if Utils.is_win32 or dct['Py_ENABLE_SHARED']:
		env['LIBPATH_PYEXT']=env['LIBPATH_PYEMBED']
		env['LIB_PYEXT']=env['LIB_PYEMBED']
	conf.to_log("Include path for Python extensions (found via distutils module): %r\n"%(dct['INCLUDEPY'],))
	env['INCLUDES_PYEXT']=[dct['INCLUDEPY']]
	env['INCLUDES_PYEMBED']=[dct['INCLUDEPY']]
	if env['CC_NAME']=='gcc':
		env.append_value('CFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT',['-fno-strict-aliasing'])
	if env['CXX_NAME']=='gcc':
		env.append_value('CXXFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT',['-fno-strict-aliasing'])
	if env.CC_NAME=="msvc":
		from distutils.msvccompiler import MSVCCompiler
		dist_compiler=MSVCCompiler()
		dist_compiler.initialize()
		env.append_value('CFLAGS_PYEXT',dist_compiler.compile_options)
		env.append_value('CXXFLAGS_PYEXT',dist_compiler.compile_options)
		env.append_value('LINKFLAGS_PYEXT',dist_compiler.ldflags_shared)
	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!')
Beispiel #11
0
def check_python_headers(conf):
    if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')
    if not conf.env['PYTHON_VERSION']:
        conf.check_python_version()
    env = conf.env
    pybin = conf.env.PYTHON
    if not pybin:
        conf.fatal('could not find the python executable')
    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s')" % x for x in v],
            ['from distutils.sysconfig import get_config_var'])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")
    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" %
                (pybin, '\n'.join(vals)))
    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]
    env['pyext_PATTERN'] = '%s' + dct['SO']
    all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEMBED')
    conf.parse_flags(all_flags, 'PYEXT')
    result = None
    name = 'python' + env['PYTHON_VERSION']
    path = env['LIBPATH_PYEMBED']
    conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
    result = conf.check(lib=name,
                        uselib='PYEMBED',
                        libpath=path,
                        mandatory=False)
    if not result:
        conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
        path = [dct['LIBDIR'] or '']
        result = conf.check(lib=name,
                            uselib='PYEMBED',
                            libpath=path,
                            mandatory=False)
    if not result:
        conf.to_log(
            "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
        )
        path = [dct['LIBPL'] or '']
        result = conf.check(lib=name,
                            uselib='PYEMBED',
                            libpath=path,
                            mandatory=False)
    if not result:
        conf.to_log(
            "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
        )
        path = [os.path.join(dct['prefix'], "libs")]
        name = 'python' + env['PYTHON_VERSION'].replace('.', '')
        result = conf.check(lib=name,
                            uselib='PYEMBED',
                            libpath=path,
                            mandatory=False)
    if result:
        env['LIBPATH_PYEMBED'] = path
        env.append_value('LIB_PYEMBED', [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")
    if (sys.platform == 'win32' or sys.platform.startswith('os2')
            or sys.platform == 'darwin' or dct['Py_ENABLE_SHARED']):
        env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
        env['LIB_PYEXT'] = env['LIB_PYEMBED']
    num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
    try:
        conf.find_program('python%s-config' % num, var='PYTHON_CONFIG')
    except conf.errors.ConfigurationError:
        conf.find_program('python-config-%s' % num,
                          var='PYTHON_CONFIG',
                          mandatory=False)
    includes = []
    if conf.env.PYTHON_CONFIG:
        for incstr in conf.cmd_and_log(
                conf.env.PYTHON +
            [conf.env.PYTHON_CONFIG, '--includes']).strip().split():
            if (incstr.startswith('-I') or incstr.startswith('/I')):
                incstr = incstr[2:]
            if incstr not in includes:
                includes.append(incstr)
        conf.to_log("Include path for Python extensions "
                    "(found via python-config --includes): %r\n" %
                    (includes, ))
        env['INCLUDES_PYEXT'] = includes
        env['INCLUDES_PYEMBED'] = includes
    else:
        conf.to_log("Include path for Python extensions "
                    "(found via distutils module): %r\n" %
                    (dct['INCLUDEPY'], ))
        env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
        env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]
    if env['CC_NAME'] == 'gcc':
        env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env['CXX_NAME'] == 'gcc':
        env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])
    conf.check(header_name='Python.h',
               define_name='HAVE_PYTHON_H',
               uselib='PYEMBED',
               fragment=FRAG,
               errmsg='Could not find the python development headers')
Beispiel #12
0
def check_python_headers(conf, features='pyembed pyext'):
	"""
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""
	features = Utils.to_list(features)
	assert ('pyembed' in features) or ('pyext' in features), "check_python_headers features must include 'pyembed' and/or 'pyext'"
	env = conf.env
	if not env.CC_NAME and not env.CXX_NAME:
		conf.fatal('load a compiler first (gcc, g++, ..)')

	# bypass all the code below for cross-compilation
	if conf.python_cross_compile(features):
		return

	if not env.PYTHON_VERSION:
		conf.check_python_version()

	pybin = env.PYTHON
	if not pybin:
		conf.fatal('Could not find the python executable')

	# so we actually do all this for compatibility reasons and for obtaining pyext_PATTERN below
	v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split()
	try:
		lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")

	vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
	conf.to_log("Configuration returned from %r:\n%s\n" % (pybin, '\n'.join(vals)))

	dct = dict(zip(v, lst))
	x = 'MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		env[x] = conf.environ[x] = dct[x]
	env.pyext_PATTERN = '%s' + dct['SO'] # not a mistake


	# Try to get pythonX.Y-config
	num = '.'.join(env.PYTHON_VERSION.split('.')[:2])
	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)

	if env.PYTHON_CONFIG:
		# python2.6-config requires 3 runs
		all_flags = [['--cflags', '--libs', '--ldflags']]
		if sys.hexversion < 0x2070000:
			all_flags = [[k] for k in all_flags[0]]

		xx = env.CXX_NAME and 'cxx' or 'c'

		if 'pyembed' in features:
			for flags in all_flags:
				conf.check_cfg(msg='Asking python-config for pyembed %r flags' % ' '.join(flags), path=env.PYTHON_CONFIG, package='', uselib_store='PYEMBED', args=flags)

			try:
				conf.test_pyembed(xx)
			except conf.errors.ConfigurationError:
				# python bug 7352
				if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
					env.append_unique('LIBPATH_PYEMBED', [dct['LIBDIR']])
					conf.test_pyembed(xx)
				else:
					raise

		if 'pyext' in features:
			for flags in all_flags:
				conf.check_cfg(msg='Asking python-config for pyext %r flags' % ' '.join(flags), path=env.PYTHON_CONFIG, package='', uselib_store='PYEXT', args=flags)

			try:
				conf.test_pyext(xx)
			except conf.errors.ConfigurationError:
				# python bug 7352
				if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
					env.append_unique('LIBPATH_PYEXT', [dct['LIBDIR']])
					conf.test_pyext(xx)
				else:
					raise

		conf.define('HAVE_PYTHON_H', 1)
		return

	# No python-config, do something else on windows systems
	all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
	conf.parse_flags(all_flags, 'PYEMBED')

	all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
	conf.parse_flags(all_flags, 'PYEXT')

	result = None
	if not dct["LDVERSION"]:
		dct["LDVERSION"] = env.PYTHON_VERSION

	# further simplification will be complicated
	for name in ('python' + dct['LDVERSION'], 'python' + env.PYTHON_VERSION + 'm', 'python' + env.PYTHON_VERSION.replace('.', '')):

		# LIBPATH_PYEMBED is already set; see if it works.
		if not result and env.LIBPATH_PYEMBED:
			path = env.LIBPATH_PYEMBED
			conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBPATH_PYEMBED' % name)

		if not result and dct['LIBDIR']:
			path = [dct['LIBDIR']]
			conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBDIR' % name)

		if not result and dct['LIBPL']:
			path = [dct['LIBPL']]
			conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in python_LIBPL' % name)

		if not result:
			path = [os.path.join(dct['prefix'], "libs")]
			conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in $prefix/libs' % name)

		if result:
			break # do not forget to set LIBPATH_PYEMBED

	if result:
		env.LIBPATH_PYEMBED = path
		env.append_value('LIB_PYEMBED', [name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")

	# under certain conditions, python extensions must link to
	# python libraries, not just python embedding programs.
	if Utils.is_win32 or dct['Py_ENABLE_SHARED']:
		env.LIBPATH_PYEXT = env.LIBPATH_PYEMBED
		env.LIB_PYEXT = env.LIB_PYEMBED

	conf.to_log("Include path for Python extensions (found via distutils module): %r\n" % (dct['INCLUDEPY'],))
	env.INCLUDES_PYEXT = [dct['INCLUDEPY']]
	env.INCLUDES_PYEMBED = [dct['INCLUDEPY']]

	# Code using the Python API needs to be compiled with -fno-strict-aliasing
	if env.CC_NAME == 'gcc':
		env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
	if env.CXX_NAME == 'gcc':
		env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

	if env.CC_NAME == "msvc":
		from distutils.msvccompiler import MSVCCompiler
		dist_compiler = MSVCCompiler()
		dist_compiler.initialize()
		env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
		env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
		env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)

	# See if it compiles
	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!')
Beispiel #13
0
def check_python_headers(conf):
    env = conf.env
    if not env["CC_NAME"] and not env["CXX_NAME"]:
        conf.fatal("load a compiler first (gcc, g++, ..)")
    if not env["PYTHON_VERSION"]:
        conf.check_python_version()
    pybin = conf.env.PYTHON
    if not pybin:
        conf.fatal("Could not find the python executable")
    v = "prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS".split()
    try:
        lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")
    vals = ["%s = %r" % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" % (pybin, "\n".join(vals)))
    dct = dict(zip(v, lst))
    x = "MACOSX_DEPLOYMENT_TARGET"
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]
    env["pyext_PATTERN"] = "%s" + dct["SO"]
    all_flags = dct["LDFLAGS"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEMBED")
    all_flags = dct["LDFLAGS"] + " " + dct["LDSHARED"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEXT")
    result = None
    for name in (
        "python" + env["PYTHON_VERSION"],
        "python" + env["PYTHON_VERSION"] + "m",
        "python" + env["PYTHON_VERSION"].replace(".", ""),
    ):
        if not result and env["LIBPATH_PYEMBED"]:
            path = env["LIBPATH_PYEMBED"]
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBPATH_PYEMBED" % name,
            )
        if not result and dct["LIBDIR"]:
            path = [dct["LIBDIR"]]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBDIR" % name,
            )
        if not result and dct["LIBPL"]:
            path = [dct["LIBPL"]]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in python_LIBPL" % name,
            )
        if not result:
            path = [os.path.join(dct["prefix"], "libs")]
            conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in $prefix/libs" % name,
            )
        if result:
            break
    if result:
        env["LIBPATH_PYEMBED"] = path
        env.append_value("LIB_PYEMBED", [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")
    if Utils.is_win32 or sys.platform.startswith("os2") or dct["Py_ENABLE_SHARED"]:
        env["LIBPATH_PYEXT"] = env["LIBPATH_PYEMBED"]
        env["LIB_PYEXT"] = env["LIB_PYEMBED"]
    num = ".".join(env["PYTHON_VERSION"].split(".")[:2])
    conf.find_program(
        ["".join(pybin) + "-config", "python%s-config" % num, "python-config-%s" % num, "python%sm-config" % num],
        var="PYTHON_CONFIG",
        display_name="python-config",
        mandatory=False,
    )
    includes = []
    if conf.env.PYTHON_CONFIG:
        for incstr in conf.cmd_and_log([conf.env.PYTHON_CONFIG, "--includes"]).strip().split():
            if incstr.startswith("-I") or incstr.startswith("/I"):
                incstr = incstr[2:]
            if incstr not in includes:
                includes.append(incstr)
        conf.to_log("Include path for Python extensions (found via python-config --includes): %r\n" % (includes,))
        env["INCLUDES_PYEXT"] = includes
        env["INCLUDES_PYEMBED"] = includes
    else:
        conf.to_log("Include path for Python extensions " "(found via distutils module): %r\n" % (dct["INCLUDEPY"],))
        env["INCLUDES_PYEXT"] = [dct["INCLUDEPY"]]
        env["INCLUDES_PYEMBED"] = [dct["INCLUDEPY"]]
    if env["CC_NAME"] == "gcc":
        env.append_value("CFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CFLAGS_PYEXT", ["-fno-strict-aliasing"])
    if env["CXX_NAME"] == "gcc":
        env.append_value("CXXFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CXXFLAGS_PYEXT", ["-fno-strict-aliasing"])
    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler

        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value("CFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("CXXFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("LINKFLAGS_PYEXT", dist_compiler.ldflags_shared)
    try:
        conf.check(header_name="Python.h", define_name="HAVE_PYTHON_H", uselib="PYEMBED", fragment=FRAG, errmsg=":-(")
    except conf.errors.ConfigurationError:
        xx = conf.env.CXX_NAME and "cxx" or "c"
        flags = ["--cflags", "--libs", "--ldflags"]
        for f in flags:
            conf.check_cfg(
                msg="Asking python-config for pyembed %s flags" % f,
                path=conf.env.PYTHON_CONFIG,
                package="",
                uselib_store="PYEMBED",
                args=[f],
            )
        conf.check(
            header_name="Python.h",
            define_name="HAVE_PYTHON_H",
            msg="Getting pyembed flags from python-config",
            fragment=FRAG,
            errmsg="Could not build a python embedded interpreter",
            features="%s %sprogram pyembed" % (xx, xx),
        )
        for f in flags:
            conf.check_cfg(
                msg="Asking python-config for pyext %s flags" % f,
                path=conf.env.PYTHON_CONFIG,
                package="",
                uselib_store="PYEXT",
                args=[f],
            )
        conf.check(
            header_name="Python.h",
            define_name="HAVE_PYTHON_H",
            msg="Getting pyext flags from python-config",
            features="%s %sshlib pyext" % (xx, xx),
            fragment=FRAG,
            errmsg="Could not build python extensions",
        )
Beispiel #14
0
def check_python_headers(conf, features="pyembed pyext"):
    """
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""
    features = Utils.to_list(features)
    assert ("pyembed" in features) or (
        "pyext" in features
    ), "check_python_headers features must include 'pyembed' and/or 'pyext'"
    env = conf.env
    if not env["CC_NAME"] and not env["CXX_NAME"]:
        conf.fatal("load a compiler first (gcc, g++, ..)")

        # bypass all the code below for cross-compilation
    if conf.python_cross_compile(features):
        return

    if not env["PYTHON_VERSION"]:
        conf.check_python_version()

    pybin = env.PYTHON
    if not pybin:
        conf.fatal("Could not find the python executable")

        # so we actually do all this for compatibility reasons and for obtaining pyext_PATTERN below
    v = "prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION".split()
    try:
        lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = ["%s = %r" % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%s\n" % (pybin, "\n".join(vals)))

    dct = dict(zip(v, lst))
    x = "MACOSX_DEPLOYMENT_TARGET"
    if dct[x]:
        env[x] = conf.environ[x] = dct[x]
    env["pyext_PATTERN"] = "%s" + dct["SO"]  # not a mistake

    # Try to get pythonX.Y-config
    num = ".".join(env["PYTHON_VERSION"].split(".")[:2])
    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,
    )

    if env.PYTHON_CONFIG:
        # python2.6-config requires 3 runs
        all_flags = [["--cflags", "--libs", "--ldflags"]]
        if sys.hexversion < 0x2070000:
            all_flags = [[k] for k in all_flags[0]]

        xx = env.CXX_NAME and "cxx" or "c"

        if "pyembed" in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg="Asking python-config for pyembed %r flags" % " ".join(flags),
                    path=env.PYTHON_CONFIG,
                    package="",
                    uselib_store="PYEMBED",
                    args=flags,
                )

            conf.check(
                header_name="Python.h",
                define_name="HAVE_PYEMBED",
                msg="Getting pyembed flags from python-config",
                fragment=FRAG,
                errmsg="Could not build a python embedded interpreter",
                features="%s %sprogram pyembed" % (xx, xx),
            )

        if "pyext" in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg="Asking python-config for pyext %r flags" % " ".join(flags),
                    path=env.PYTHON_CONFIG,
                    package="",
                    uselib_store="PYEXT",
                    args=flags,
                )

            conf.check(
                header_name="Python.h",
                define_name="HAVE_PYEXT",
                msg="Getting pyext flags from python-config",
                features="%s %sshlib pyext" % (xx, xx),
                fragment=FRAG,
                errmsg="Could not build python extensions",
            )

        conf.define("HAVE_PYTHON_H", 1)
        return

        # No python-config, do something else on windows systems
    all_flags = dct["LDFLAGS"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEMBED")

    all_flags = dct["LDFLAGS"] + " " + dct["LDSHARED"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEXT")

    result = None
    if not dct["LDVERSION"]:
        dct["LDVERSION"] = env["PYTHON_VERSION"]

        # further simplification will be complicated
    for name in (
        "python" + dct["LDVERSION"],
        "python" + env["PYTHON_VERSION"] + "m",
        "python" + env["PYTHON_VERSION"].replace(".", ""),
    ):

        # LIBPATH_PYEMBED is already set; see if it works.
        if not result and env["LIBPATH_PYEMBED"]:
            path = env["LIBPATH_PYEMBED"]
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBPATH_PYEMBED" % name,
            )

        if not result and dct["LIBDIR"]:
            path = [dct["LIBDIR"]]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in LIBDIR" % name,
            )

        if not result and dct["LIBPL"]:
            path = [dct["LIBPL"]]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in python_LIBPL" % name,
            )

        if not result:
            path = [os.path.join(dct["prefix"], "libs")]
            conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
            result = conf.check(
                lib=name,
                uselib="PYEMBED",
                libpath=path,
                mandatory=False,
                msg="Checking for library %s in $prefix/libs" % name,
            )

        if result:
            break  # do not forget to set LIBPATH_PYEMBED

    if result:
        env["LIBPATH_PYEMBED"] = path
        env.append_value("LIB_PYEMBED", [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")

        # under certain conditions, python extensions must link to
        # python libraries, not just python embedding programs.
    if Utils.is_win32 or dct["Py_ENABLE_SHARED"]:
        env["LIBPATH_PYEXT"] = env["LIBPATH_PYEMBED"]
        env["LIB_PYEXT"] = env["LIB_PYEMBED"]

    conf.to_log("Include path for Python extensions (found via distutils module): %r\n" % (dct["INCLUDEPY"],))
    env["INCLUDES_PYEXT"] = [dct["INCLUDEPY"]]
    env["INCLUDES_PYEMBED"] = [dct["INCLUDEPY"]]

    # Code using the Python API needs to be compiled with -fno-strict-aliasing
    if env["CC_NAME"] == "gcc":
        env.append_value("CFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CFLAGS_PYEXT", ["-fno-strict-aliasing"])
    if env["CXX_NAME"] == "gcc":
        env.append_value("CXXFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CXXFLAGS_PYEXT", ["-fno-strict-aliasing"])

    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler

        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value("CFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("CXXFLAGS_PYEXT", dist_compiler.compile_options)
        env.append_value("LINKFLAGS_PYEXT", dist_compiler.ldflags_shared)

        # See if it compiles
    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!",
    )
Beispiel #15
0
def check_python_headers(conf):
	if not conf.env['CC_NAME']and not conf.env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')
	if not conf.env['PYTHON_VERSION']:
		conf.check_python_version()
	env=conf.env
	pybin=conf.env.PYTHON
	if not pybin:
		conf.fatal('could not find the python executable')
	v='prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
	try:
		lst=conf.get_python_variables(["get_config_var('%s')"%x for x in v],['from distutils.sysconfig import get_config_var'])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")
	vals=['%s = %r'%(x,y)for(x,y)in zip(v,lst)]
	conf.to_log("Configuration returned from %r:\n%r\n"%(pybin,'\n'.join(vals)))
	dct=dict(zip(v,lst))
	x='MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x]=conf.environ[x]=dct[x]
	env['pyext_PATTERN']='%s'+dct['SO']
	all_flags=dct['LDFLAGS']+' '+dct['LDSHARED']+' '+dct['CFLAGS']
	conf.parse_flags(all_flags,'PYEMBED')
	conf.parse_flags(all_flags,'PYEXT')
	result=None
	name='python'+env['PYTHON_VERSION']
	path=env['LIBPATH_PYEMBED']
	conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n"%path)
	result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
	if not result:
		conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n"%path)
		path=[dct['LIBDIR']or'']
		result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
	if not result:
		conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
		path=[dct['LIBPL']or'']
		result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
	if not result:
		conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
		path=[os.path.join(dct['prefix'],"libs")]
		name='python'+env['PYTHON_VERSION'].replace('.','')
		result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False)
	if result:
		env['LIBPATH_PYEMBED']=path
		env.append_value('LIB_PYEMBED',[name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")
	if(sys.platform=='win32'or sys.platform.startswith('os2')or sys.platform=='darwin'or dct['Py_ENABLE_SHARED']):
		env['LIBPATH_PYEXT']=env['LIBPATH_PYEMBED']
		env['LIB_PYEXT']=env['LIB_PYEMBED']
	num='.'.join(env['PYTHON_VERSION'].split('.')[:2])
	try:
		conf.find_program('python%s-config'%num,var='PYTHON_CONFIG')
	except conf.errors.ConfigurationError:
		conf.find_program('python-config-%s'%num,var='PYTHON_CONFIG',mandatory=False)
	includes=[]
	if conf.env.PYTHON_CONFIG:
		for incstr in conf.cmd_and_log(conf.env.PYTHON_CONFIG + ' --includes').strip().split():
			if(incstr.startswith('-I')or incstr.startswith('/I')):
				incstr=incstr[2:]
			if incstr not in includes:
				includes.append(incstr)
		conf.to_log("Include path for Python extensions ""(found via python-config --includes): %r\n"%(includes,))
		env['INCLUDES_PYEXT']=includes
		env['INCLUDES_PYEMBED']=includes
	else:
		conf.to_log("Include path for Python extensions ""(found via distutils module): %r\n"%(dct['INCLUDEPY'],))
		env['INCLUDES_PYEXT']=[dct['INCLUDEPY']]
		env['INCLUDES_PYEMBED']=[dct['INCLUDEPY']]
	if env['CC_NAME']=='gcc':
		env.append_value('CFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT',['-fno-strict-aliasing'])
	if env['CXX_NAME']=='gcc':
		env.append_value('CXXFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT',['-fno-strict-aliasing'])
Beispiel #16
0
def check_python_headers(conf):
    env = conf.env
    if not env['CC_NAME'] and not env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')
    if not env['PYTHON_VERSION']:
        conf.check_python_version()
    pybin = conf.env.PYTHON
    if not pybin:
        conf.fatal('Could not find the python executable')
    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")
    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" %
                (pybin, '\n'.join(vals)))
    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]
    if not env.pyext_PATTERN:
        if dct['SO']:
            env.pyext_PATTERN = '%s' + dct['SO']
        else:
            env.pyext_PATTERN = (conf.env.cshlib_PATTERN
                                 or conf.env.cxxshlib_PATTERN).lstrip('lib')
    num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
    conf.find_program([
        ''.join(pybin) + '-config',
        'python%s-config' % num,
        'python-config-%s' % num,
        'python%sm-config' % num
    ],
                      var='PYTHON_CONFIG',
                      msg="python-config")
    all_flags = [['--cflags', '--libs', '--ldflags']]
    if sys.hexversion < 0x2060000:
        all_flags = [[x] for x in all_flags[0]]
    xx = conf.env.CXX_NAME and 'cxx' or 'c'
    for flags in all_flags:
        conf.check_cfg(msg='Asking python-config for pyembed %r flags' %
                       ' '.join(flags),
                       path=conf.env.PYTHON_CONFIG,
                       package='',
                       uselib_store='PYEMBED',
                       args=flags)
    conf.check(header_name='Python.h',
               define_name='HAVE_PYEMBED',
               msg='Getting pyembed flags from python-config',
               fragment=FRAG,
               errmsg='Could not build a python embedded interpreter',
               features='%s %sprogram pyembed' % (xx, xx))
    for flags in all_flags:
        conf.check_cfg(msg='Asking python-config for pyext %r flags' %
                       ' '.join(flags),
                       path=conf.env.PYTHON_CONFIG,
                       package='',
                       uselib_store='PYEXT',
                       args=flags)
    conf.check(header_name='Python.h',
               define_name='HAVE_PYEXT',
               msg='Getting pyext flags from python-config',
               features='%s %sshlib pyext' % (xx, xx),
               fragment=FRAG,
               errmsg='Could not build python extensions')
    conf.define('HAVE_PYTHON_H', 1)
Beispiel #17
0
def check_python_headers(conf, features='pyembed pyext'):
    features = Utils.to_list(features)
    assert ('pyembed' in features) or (
        'pyext' in features
    ), "check_python_headers features must include 'pyembed' and/or 'pyext'"
    env = conf.env
    if not env['CC_NAME'] and not env['CXX_NAME']:
        conf.fatal('load a compiler first (gcc, g++, ..)')
    if conf.python_cross_compile(features):
        return
    if not env['PYTHON_VERSION']:
        conf.check_python_version()
    pybin = env.PYTHON
    if not pybin:
        conf.fatal('Could not find the python executable')
    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")
    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%s\n" %
                (pybin, '\n'.join(vals)))
    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        env[x] = conf.environ[x] = dct[x]
    env['pyext_PATTERN'] = '%s' + dct['SO']
    num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
    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)
    if env.PYTHON_CONFIG:
        all_flags = [['--cflags', '--libs', '--ldflags']]
        if sys.hexversion < 0x2070000:
            all_flags = [[k] for k in all_flags[0]]
        xx = env.CXX_NAME and 'cxx' or 'c'
        if 'pyembed' in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg='Asking python-config for pyembed %r flags' %
                    ' '.join(flags),
                    path=env.PYTHON_CONFIG,
                    package='',
                    uselib_store='PYEMBED',
                    args=flags)
            try:
                conf.test_pyembed(xx)
            except conf.errors.ConfigurationError:
                if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
                    env.append_unique('LIBPATH_PYEMBED', [dct['LIBDIR']])
                    conf.test_pyembed(xx)
                else:
                    raise
        if 'pyext' in features:
            for flags in all_flags:
                conf.check_cfg(msg='Asking python-config for pyext %r flags' %
                               ' '.join(flags),
                               path=env.PYTHON_CONFIG,
                               package='',
                               uselib_store='PYEXT',
                               args=flags)
            try:
                conf.test_pyext(xx)
            except conf.errors.ConfigurationError:
                if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
                    env.append_unique('LIBPATH_PYEXT', [dct['LIBDIR']])
                    conf.test_pyext(xx)
                else:
                    raise
        conf.define('HAVE_PYTHON_H', 1)
        return
    all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEMBED')
    all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEXT')
    result = None
    if not dct["LDVERSION"]:
        dct["LDVERSION"] = env['PYTHON_VERSION']
    for name in ('python' + dct['LDVERSION'],
                 'python' + env['PYTHON_VERSION'] + 'm',
                 'python' + env['PYTHON_VERSION'].replace('.', '')):
        if not result and env['LIBPATH_PYEMBED']:
            path = env['LIBPATH_PYEMBED']
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib='PYEMBED',
                libpath=path,
                mandatory=False,
                msg='Checking for library %s in LIBPATH_PYEMBED' % name)
        if not result and dct['LIBDIR']:
            path = [dct['LIBDIR']]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in LIBDIR' % name)
        if not result and dct['LIBPL']:
            path = [dct['LIBPL']]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in python_LIBPL' %
                                name)
        if not result:
            path = [os.path.join(dct['prefix'], "libs")]
            conf.to_log(
                "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in $prefix/libs' %
                                name)
        if result:
            break
    if result:
        env['LIBPATH_PYEMBED'] = path
        env.append_value('LIB_PYEMBED', [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")
    if Utils.is_win32 or dct['Py_ENABLE_SHARED']:
        env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
        env['LIB_PYEXT'] = env['LIB_PYEMBED']
    conf.to_log(
        "Include path for Python extensions (found via distutils module): %r\n"
        % (dct['INCLUDEPY'], ))
    env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
    env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]
    if env['CC_NAME'] == 'gcc':
        env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env['CXX_NAME'] == 'gcc':
        env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler
        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)
    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!'
    )
Beispiel #18
0
def check_python_headers(conf):
	"""Check for headers and libraries necessary to extend or embed python.

	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added for uselib

	PYEXT: for compiling python extensions
	PYEMBED: for embedding a python interpreter"""

	if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')

	if not conf.env['PYTHON_VERSION']:
		conf.check_python_version()

	env = conf.env
	python = env['PYTHON']
	if not python:
		conf.fatal('could not find the python executable')

	v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
	try:
		lst = conf.get_python_variables(python, ["get_config_var('%s')" % x for x in v],
			['from distutils.sysconfig import get_config_var'])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")

	vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
	conf.to_log("Configuration returned from %r:\n%r\n" % (python, '\n'.join(vals)))

	dct = dict(zip(v, lst))
	x = 'MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x] = conf.environ[x] = dct[x]

	env['pyext_PATTERN'] = '%s' + dct['SO'] # not a mistake

	# Check for python libraries for embedding

	all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
	conf.parse_flags(all_flags, 'PYEMBED')
	conf.parse_flags(all_flags, 'PYEXT')

	result = None
	name = 'python' + env['PYTHON_VERSION']

	# LIBPATH_PYEMBED is already set; see if it works.
	path = env['LIBPATH_PYEMBED']
	conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
	result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False)

	if not result:
		conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
		path = [dct['LIBDIR'] or '']
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False)

	if not result:
		conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
		path = [dct['LIBPL'] or '']
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False)

	if not result:
		conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
		path = [os.path.join(dct['prefix'], "libs")]
		name = 'python' + env['PYTHON_VERSION'].replace('.', '')
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False)

	if result:
		env['LIBPATH_PYEMBED'] = path
		env.append_value('LIB_PYEMBED', [name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")

	# under certain conditions, python extensions must link to
	# python libraries, not just python embedding programs.
	if (sys.platform == 'win32' or sys.platform.startswith('os2')
		or sys.platform == 'darwin' or dct['Py_ENABLE_SHARED']):
		env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
		env['LIB_PYEXT'] = env['LIB_PYEMBED']

	# We check that pythonX.Y-config exists, and if it exists we
	# use it to get only the includes, else fall back to distutils.
	num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
	try:
		conf.find_program(
			'python%s-config' % num,
			var='PYTHON_CONFIG')
	except conf.errors.ConfigurationError:
		conf.find_program(
			'python-config-%s' % num,
			var='PYTHON_CONFIG', mandatory=False)

	includes = []
	if conf.env.PYTHON_CONFIG:
		for incstr in conf.cmd_and_log("%s %s --includes" % (python, conf.env.PYTHON_CONFIG)).strip().split():
			# strip the -I or /I
			if (incstr.startswith('-I') or incstr.startswith('/I')):
				incstr = incstr[2:]
			# append include path, unless already given
			if incstr not in includes:
				includes.append(incstr)
		conf.to_log("Include path for Python extensions "
			       "(found via python-config --includes): %r\n" % (includes,))
		env['INCLUDES_PYEXT'] = includes
		env['INCLUDES_PYEMBED'] = includes
	else:
		conf.to_log("Include path for Python extensions "
			       "(found via distutils module): %r\n" % (dct['INCLUDEPY'],))
		env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
		env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]

	# Code using the Python API needs to be compiled with -fno-strict-aliasing
	if env['CC_NAME'] == 'gcc':
		env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
	if env['CXX_NAME'] == 'gcc':
		env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

	# See if it compiles
	conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H',
		   uselib='PYEMBED', fragment=FRAG,
		   errmsg='Could not find the python development headers')
Beispiel #19
0
def check_python_headers(conf):
    """
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""

    if not conf.env["CC_NAME"] and not conf.env["CXX_NAME"]:
        conf.fatal("load a compiler first (gcc, g++, ..)")

    if not conf.env["PYTHON_VERSION"]:
        conf.check_python_version()

    env = conf.env
    python = env["PYTHON"]
    if not python:
        conf.fatal("could not find the python executable")

    v = "prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS".split()
    try:
        lst = conf.get_python_variables(
            python, ["get_config_var('%s')" % x for x in v], ["from distutils.sysconfig import get_config_var"]
        )
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = ["%s = %r" % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%r\n" % (python, "\n".join(vals)))

    dct = dict(zip(v, lst))
    x = "MACOSX_DEPLOYMENT_TARGET"
    if dct[x]:
        conf.env[x] = conf.environ[x] = dct[x]

    env["pyext_PATTERN"] = "%s" + dct["SO"]  # not a mistake

    # Check for python libraries for embedding

    all_flags = dct["LDFLAGS"] + " " + dct["LDSHARED"] + " " + dct["CFLAGS"]
    conf.parse_flags(all_flags, "PYEMBED")
    conf.parse_flags(all_flags, "PYEXT")

    result = None
    name = "python" + env["PYTHON_VERSION"]

    # LIBPATH_PYEMBED is already set; see if it works.
    path = env["LIBPATH_PYEMBED"]
    conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
    result = conf.check(lib=name, uselib="PYEMBED", libpath=path, mandatory=False)

    if not result:
        conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
        path = [dct["LIBDIR"] or ""]
        result = conf.check(lib=name, uselib="PYEMBED", libpath=path, mandatory=False)

    if not result:
        conf.to_log(
            "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
        )
        path = [dct["LIBPL"] or ""]
        result = conf.check(lib=name, uselib="PYEMBED", libpath=path, mandatory=False)

    if not result:
        conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
        path = [os.path.join(dct["prefix"], "libs")]
        name = "python" + env["PYTHON_VERSION"].replace(".", "")
        result = conf.check(lib=name, uselib="PYEMBED", libpath=path, mandatory=False)

    if result:
        env["LIBPATH_PYEMBED"] = path
        env.append_value("LIB_PYEMBED", [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")

        # under certain conditions, python extensions must link to
        # python libraries, not just python embedding programs.
    if sys.platform == "win32" or sys.platform.startswith("os2") or sys.platform == "darwin" or dct["Py_ENABLE_SHARED"]:
        env["LIBPATH_PYEXT"] = env["LIBPATH_PYEMBED"]
        env["LIB_PYEXT"] = env["LIB_PYEMBED"]

        # We check that pythonX.Y-config exists, and if it exists we
        # use it to get only the includes, else fall back to distutils.
    num = ".".join(env["PYTHON_VERSION"].split(".")[:2])
    try:
        conf.find_program("python%s-config" % num, var="PYTHON_CONFIG")
    except conf.errors.ConfigurationError:
        conf.find_program("python-config-%s" % num, var="PYTHON_CONFIG", mandatory=False)

    includes = []
    if conf.env.PYTHON_CONFIG:
        for incstr in conf.cmd_and_log("%s %s --includes" % (python, conf.env.PYTHON_CONFIG)).strip().split():
            # strip the -I or /I
            if incstr.startswith("-I") or incstr.startswith("/I"):
                incstr = incstr[2:]
                # append include path, unless already given
            if incstr not in includes:
                includes.append(incstr)
        conf.to_log("Include path for Python extensions " "(found via python-config --includes): %r\n" % (includes,))
        env["INCLUDES_PYEXT"] = includes
        env["INCLUDES_PYEMBED"] = includes
    else:
        conf.to_log("Include path for Python extensions " "(found via distutils module): %r\n" % (dct["INCLUDEPY"],))
        env["INCLUDES_PYEXT"] = [dct["INCLUDEPY"]]
        env["INCLUDES_PYEMBED"] = [dct["INCLUDEPY"]]

        # Code using the Python API needs to be compiled with -fno-strict-aliasing
    if env["CC_NAME"] == "gcc":
        env.append_value("CFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CFLAGS_PYEXT", ["-fno-strict-aliasing"])
    if env["CXX_NAME"] == "gcc":
        env.append_value("CXXFLAGS_PYEMBED", ["-fno-strict-aliasing"])
        env.append_value("CXXFLAGS_PYEXT", ["-fno-strict-aliasing"])

        # See if it compiles
    conf.check(
        header_name="Python.h",
        define_name="HAVE_PYTHON_H",
        uselib="PYEMBED",
        fragment=FRAG,
        errmsg="Could not find the python development headers",
    )
def check_python_headers(conf, features='pyembed pyext'):
    """
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""
    features = Utils.to_list(features)
    assert ('pyembed' in features) or (
        'pyext' in features
    ), "check_python_headers features must include 'pyembed' and/or 'pyext'"
    env = conf.env
    if not env.CC_NAME and not env.CXX_NAME:
        conf.fatal('load a compiler first (gcc, g++, ..)')

    # bypass all the code below for cross-compilation
    if conf.python_cross_compile(features):
        return

    if not env.PYTHON_VERSION:
        conf.check_python_version()

    pybin = env.PYTHON
    if not pybin:
        conf.fatal('Could not find the python executable')

    # so we actually do all this for compatibility reasons and for obtaining pyext_PATTERN below
    v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split(
    )
    try:
        lst = conf.get_python_variables(
            ["get_config_var('%s') or ''" % x for x in v])
    except RuntimeError:
        conf.fatal("Python development headers not found (-v for details).")

    vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
    conf.to_log("Configuration returned from %r:\n%s\n" %
                (pybin, '\n'.join(vals)))

    dct = dict(zip(v, lst))
    x = 'MACOSX_DEPLOYMENT_TARGET'
    if dct[x]:
        env[x] = conf.environ[x] = dct[x]
    env.pyext_PATTERN = '%s' + dct['SO']  # not a mistake

    # Try to get pythonX.Y-config
    num = '.'.join(env.PYTHON_VERSION.split('.')[:2])
    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)

    if env.PYTHON_CONFIG:
        # python2.6-config requires 3 runs
        all_flags = [['--cflags', '--libs', '--ldflags']]
        if sys.hexversion < 0x2070000:
            all_flags = [[k] for k in all_flags[0]]

        xx = env.CXX_NAME and 'cxx' or 'c'

        if 'pyembed' in features:
            for flags in all_flags:
                conf.check_cfg(
                    msg='Asking python-config for pyembed %r flags' %
                    ' '.join(flags),
                    path=env.PYTHON_CONFIG,
                    package='',
                    uselib_store='PYEMBED',
                    args=flags)

            try:
                conf.test_pyembed(xx)
            except conf.errors.ConfigurationError:
                # python bug 7352
                if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
                    env.append_unique('LIBPATH_PYEMBED', [dct['LIBDIR']])
                    conf.test_pyembed(xx)
                else:
                    raise

        if 'pyext' in features:
            for flags in all_flags:
                conf.check_cfg(msg='Asking python-config for pyext %r flags' %
                               ' '.join(flags),
                               path=env.PYTHON_CONFIG,
                               package='',
                               uselib_store='PYEXT',
                               args=flags)

            try:
                conf.test_pyext(xx)
            except conf.errors.ConfigurationError:
                # python bug 7352
                if dct['Py_ENABLE_SHARED'] and dct['LIBDIR']:
                    env.append_unique('LIBPATH_PYEXT', [dct['LIBDIR']])
                    conf.test_pyext(xx)
                else:
                    raise

        conf.define('HAVE_PYTHON_H', 1)
        return

    # No python-config, do something else on windows systems
    all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEMBED')

    all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
    conf.parse_flags(all_flags, 'PYEXT')

    result = None
    if not dct["LDVERSION"]:
        dct["LDVERSION"] = env.PYTHON_VERSION

    # further simplification will be complicated
    for name in ('python' + dct['LDVERSION'],
                 'python' + env.PYTHON_VERSION + 'm',
                 'python' + env.PYTHON_VERSION.replace('.', '')):

        # LIBPATH_PYEMBED is already set; see if it works.
        if not result and env.LIBPATH_PYEMBED:
            path = env.LIBPATH_PYEMBED
            conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
            result = conf.check(
                lib=name,
                uselib='PYEMBED',
                libpath=path,
                mandatory=False,
                msg='Checking for library %s in LIBPATH_PYEMBED' % name)

        if not result and dct['LIBDIR']:
            path = [dct['LIBDIR']]
            conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in LIBDIR' % name)

        if not result and dct['LIBPL']:
            path = [dct['LIBPL']]
            conf.to_log(
                "\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in python_LIBPL' %
                                name)

        if not result:
            path = [os.path.join(dct['prefix'], "libs")]
            conf.to_log(
                "\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n"
            )
            result = conf.check(lib=name,
                                uselib='PYEMBED',
                                libpath=path,
                                mandatory=False,
                                msg='Checking for library %s in $prefix/libs' %
                                name)

        if result:
            break  # do not forget to set LIBPATH_PYEMBED

    if result:
        env.LIBPATH_PYEMBED = path
        env.append_value('LIB_PYEMBED', [name])
    else:
        conf.to_log("\n\n### LIB NOT FOUND\n")

    # under certain conditions, python extensions must link to
    # python libraries, not just python embedding programs.
    if Utils.is_win32 or dct['Py_ENABLE_SHARED']:
        env.LIBPATH_PYEXT = env.LIBPATH_PYEMBED
        env.LIB_PYEXT = env.LIB_PYEMBED

    conf.to_log(
        "Include path for Python extensions (found via distutils module): %r\n"
        % (dct['INCLUDEPY'], ))
    env.INCLUDES_PYEXT = [dct['INCLUDEPY']]
    env.INCLUDES_PYEMBED = [dct['INCLUDEPY']]

    # Code using the Python API needs to be compiled with -fno-strict-aliasing
    if env.CC_NAME == 'gcc':
        env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
    if env.CXX_NAME == 'gcc':
        env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
        env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

    if env.CC_NAME == "msvc":
        from distutils.msvccompiler import MSVCCompiler
        dist_compiler = MSVCCompiler()
        dist_compiler.initialize()
        env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
        env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)

    # See if it compiles
    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!'
    )
Beispiel #21
0
def check_python_headers(conf):
	if not conf.env['CC_NAME']and not conf.env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')
	if not conf.env['PYTHON_VERSION']:
		conf.check_python_version()
	env=conf.env
	pybin=conf.env.PYTHON
	if not pybin:
		conf.fatal('could not find the python executable')
	v='prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS'.split()
	try:
		lst=conf.get_python_variables(["get_config_var('%s') or ''"%x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")
	vals=['%s = %r'%(x,y)for(x,y)in zip(v,lst)]
	conf.to_log("Configuration returned from %r:\n%r\n"%(pybin,'\n'.join(vals)))
	dct=dict(zip(v,lst))
	x='MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x]=conf.environ[x]=dct[x]
	env['pyext_PATTERN']='%s'+dct['SO']
	all_flags=dct['LDFLAGS']+' '+dct['CFLAGS']
	conf.parse_flags(all_flags,'PYEMBED')
	all_flags=dct['LDFLAGS']+' '+dct['LDSHARED']+' '+dct['CFLAGS']
	conf.parse_flags(all_flags,'PYEXT')
	result=None
	for name in('python'+env['PYTHON_VERSION'],'python'+env['PYTHON_VERSION'].replace('.','')):
		if not result and env['LIBPATH_PYEMBED']:
			path=env['LIBPATH_PYEMBED']
			conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n"%path)
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in LIBPATH_PYEMBED'%name)
		if not result and dct['LIBDIR']:
			path=[dct['LIBDIR']]
			conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n"%path)
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in LIBDIR'%name)
		if not result and dct['LIBPL']:
			path=[dct['LIBPL']]
			conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in python_LIBPL'%name)
		if not result:
			path=[os.path.join(dct['prefix'],"libs")]
			conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
			result=conf.check(lib=name,uselib='PYEMBED',libpath=path,mandatory=False,msg='Checking for library %s in $prefix/libs'%name)
		if result:
			break
	if result:
		env['LIBPATH_PYEMBED']=path
		env.append_value('LIB_PYEMBED',[name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")
	if(Utils.is_win32 or sys.platform.startswith('os2')or dct['Py_ENABLE_SHARED']):
		env['LIBPATH_PYEXT']=env['LIBPATH_PYEMBED']
		env['LIB_PYEXT']=env['LIB_PYEMBED']
	num='.'.join(env['PYTHON_VERSION'].split('.')[:2])
	conf.find_program(['python%s-config'%num,'python-config-%s'%num,'python%sm-config'%num],var='PYTHON_CONFIG',mandatory=False)
	includes=[]
	if conf.env.PYTHON_CONFIG:
		for incstr in conf.cmd_and_log([conf.env.PYTHON_CONFIG,'--includes']).strip().split():
			if(incstr.startswith('-I')or incstr.startswith('/I')):
				incstr=incstr[2:]
			if incstr not in includes:
				includes.append(incstr)
		conf.to_log("Include path for Python extensions (found via python-config --includes): %r\n"%(includes,))
		env['INCLUDES_PYEXT']=includes
		env['INCLUDES_PYEMBED']=includes
	else:
		conf.to_log("Include path for Python extensions ""(found via distutils module): %r\n"%(dct['INCLUDEPY'],))
		env['INCLUDES_PYEXT']=[dct['INCLUDEPY']]
		env['INCLUDES_PYEMBED']=[dct['INCLUDEPY']]
	if env['CC_NAME']=='gcc':
		env.append_value('CFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT',['-fno-strict-aliasing'])
	if env['CXX_NAME']=='gcc':
		env.append_value('CXXFLAGS_PYEMBED',['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT',['-fno-strict-aliasing'])
	if env.CC_NAME=="msvc":
		from distutils.msvccompiler import MSVCCompiler
		dist_compiler=MSVCCompiler()
		dist_compiler.initialize()
		env.append_value('CFLAGS_PYEXT',dist_compiler.compile_options)
		env.append_value('CXXFLAGS_PYEXT',dist_compiler.compile_options)
		env.append_value('LINKFLAGS_PYEXT',dist_compiler.ldflags_shared)
	try:
		conf.check(header_name='Python.h',define_name='HAVE_PYTHON_H',uselib='PYEMBED',fragment=FRAG,errmsg='Could not find the python development headers')
	except conf.errors.ConfigurationError:
		conf.check_cfg(path=conf.env.PYTHON_CONFIG,package='',uselib_store='PYEMBED',args=['--cflags','--libs'])
		conf.check(header_name='Python.h',define_name='HAVE_PYTHON_H',msg='Getting the python flags from python-config',uselib='PYEMBED',fragment=FRAG,errmsg='Could not find the python development headers elsewhere')
Beispiel #22
0
def check_python_headers(conf):
	"""
	Check for headers and libraries necessary to extend or embed python by using the module *distutils*.
	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added:

	* PYEXT: for compiling python extensions
	* PYEMBED: for embedding a python interpreter
	"""

	# FIXME rewrite

	env = conf.env
	if not env['CC_NAME'] and not env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')

	if not env['PYTHON_VERSION']:
		conf.check_python_version()

	pybin = conf.env.PYTHON
	if not pybin:
		conf.fatal('Could not find the python executable')

	v = 'prefix SO LDFLAGS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET LDSHARED CFLAGS LDVERSION'.split()
	try:
		lst = conf.get_python_variables(["get_config_var('%s') or ''" % x for x in v])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")

	vals = ['%s = %r' % (x, y) for (x, y) in zip(v, lst)]
	conf.to_log("Configuration returned from %r:\n%r\n" % (pybin, '\n'.join(vals)))

	dct = dict(zip(v, lst))
	x = 'MACOSX_DEPLOYMENT_TARGET'
	if dct[x]:
		conf.env[x] = conf.environ[x] = dct[x]

	env['pyext_PATTERN'] = '%s' + dct['SO'] # not a mistake

	# Check for python libraries for embedding

	all_flags = dct['LDFLAGS'] + ' ' + dct['CFLAGS']
	conf.parse_flags(all_flags, 'PYEMBED')

	all_flags = dct['LDFLAGS'] + ' ' + dct['LDSHARED'] + ' ' + dct['CFLAGS']
	conf.parse_flags(all_flags, 'PYEXT')

	result = None
	#name = 'python' + env['PYTHON_VERSION']

	if not dct["LDVERSION"]:
		dct["LDVERSION"] = env['PYTHON_VERSION']

	# TODO simplify this
	for name in ('python' + dct['LDVERSION'], 'python' + env['PYTHON_VERSION'] + 'm', 'python' + env['PYTHON_VERSION'].replace('.', '')):

		# LIBPATH_PYEMBED is already set; see if it works.
		if not result and env['LIBPATH_PYEMBED']:
			path = env['LIBPATH_PYEMBED']
			conf.to_log("\n\n# Trying default LIBPATH_PYEMBED: %r\n" % path)
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBPATH_PYEMBED' % name)

		if not result and dct['LIBDIR']:
			path = [dct['LIBDIR']]
			conf.to_log("\n\n# try again with -L$python_LIBDIR: %r\n" % path)
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in LIBDIR' % name)

		if not result and dct['LIBPL']:
			path = [dct['LIBPL']]
			conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in python_LIBPL' % name)

		if not result:
			path = [os.path.join(dct['prefix'], "libs")]
			conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
			result = conf.check(lib=name, uselib='PYEMBED', libpath=path, mandatory=False, msg='Checking for library %s in $prefix/libs' % name)

		if result:
			break # do not forget to set LIBPATH_PYEMBED

	if result:
		env['LIBPATH_PYEMBED'] = path
		env.append_value('LIB_PYEMBED', [name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")

	# under certain conditions, python extensions must link to
	# python libraries, not just python embedding programs.
	if (Utils.is_win32 or sys.platform.startswith('os2')
		or dct['Py_ENABLE_SHARED']):
		env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
		env['LIB_PYEXT'] = env['LIB_PYEMBED']

	# We check that pythonX.Y-config exists, and if it exists we
	# use it to get only the includes, else fall back to distutils.
	num = '.'.join(env['PYTHON_VERSION'].split('.')[:2])
	conf.find_program([''.join(pybin) + '-config', 'python%s-config' % num, 'python-config-%s' % num, 'python%sm-config' % num], var='PYTHON_CONFIG', mandatory=False)

	includes = []
	if conf.env.PYTHON_CONFIG:
		for incstr in conf.cmd_and_log([ conf.env.PYTHON_CONFIG, '--includes']).strip().split():
			# strip the -I or /I
			if (incstr.startswith('-I') or incstr.startswith('/I')):
				incstr = incstr[2:]
			# append include path, unless already given
			if incstr not in includes:
				includes.append(incstr)
		conf.to_log("Include path for Python extensions (found via python-config --includes): %r\n" % (includes,))
		env['INCLUDES_PYEXT'] = includes
		env['INCLUDES_PYEMBED'] = includes
	else:
		conf.to_log("Include path for Python extensions "
			       "(found via distutils module): %r\n" % (dct['INCLUDEPY'],))
		env['INCLUDES_PYEXT'] = [dct['INCLUDEPY']]
		env['INCLUDES_PYEMBED'] = [dct['INCLUDEPY']]

	# Code using the Python API needs to be compiled with -fno-strict-aliasing
	if env['CC_NAME'] == 'gcc':
		env.append_value('CFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CFLAGS_PYEXT', ['-fno-strict-aliasing'])
	if env['CXX_NAME'] == 'gcc':
		env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

	if env.CC_NAME == "msvc":
		from distutils.msvccompiler import MSVCCompiler
		dist_compiler = MSVCCompiler()
		dist_compiler.initialize()
		env.append_value('CFLAGS_PYEXT', dist_compiler.compile_options)
		env.append_value('CXXFLAGS_PYEXT', dist_compiler.compile_options)
		env.append_value('LINKFLAGS_PYEXT', dist_compiler.ldflags_shared)

	# See if it compiles
	try:
		conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H',
		   uselib='PYEMBED', fragment=FRAG,
		   errmsg=':-(')
	except conf.errors.ConfigurationError:
		# python3.2, oh yeah
		xx = conf.env.CXX_NAME and 'cxx' or 'c'

		flags = ['--cflags', '--libs', '--ldflags']

		for f in flags:
			conf.check_cfg(msg='Asking python-config for pyembed %s flags' % f,
				path=conf.env.PYTHON_CONFIG, package='', uselib_store='PYEMBED', args=[f])
		conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H', msg='Getting pyembed flags from python-config',
			fragment=FRAG, errmsg='Could not build a python embedded interpreter',
			features='%s %sprogram pyembed' % (xx, xx))

		for f in flags:
			conf.check_cfg(msg='Asking python-config for pyext %s flags' % f,
				path=conf.env.PYTHON_CONFIG, package='', uselib_store='PYEXT', args=[f])
		conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H', msg='Getting pyext flags from python-config',
			features='%s %sshlib pyext' % (xx, xx), fragment=FRAG, errmsg='Could not build python extensions')
Beispiel #23
0
Datei: python.py Projekt: zsx/waf
def check_python_headers(conf):
	"""Check for headers and libraries necessary to extend or embed python.

	On success the environment variables xxx_PYEXT and xxx_PYEMBED are added for uselib

	PYEXT: for compiling python extensions
	PYEMBED: for embedding a python interpreter"""

	if not conf.env['CC_NAME'] and not conf.env['CXX_NAME']:
		conf.fatal('load a compiler first (gcc, g++, ..)')

	if not conf.env['PYTHON_VERSION']:
		conf.check_python_version()

	env = conf.env
	python = env['PYTHON']
	if not python:
		conf.fatal('could not find the python executable')

	## On Mac OSX we need to use mac bundles for python plugins
	if Options.platform == 'darwin':
		conf.check_tool('osx')

	try:
		# Get some python configuration variables using distutils
		v = 'prefix SO SYSLIBS LDFLAGS SHLIBS LIBDIR LIBPL INCLUDEPY Py_ENABLE_SHARED MACOSX_DEPLOYMENT_TARGET'.split()
		(python_prefix, python_SO, python_SYSLIBS, python_LDFLAGS, python_SHLIBS,
		 python_LIBDIR, python_LIBPL, INCLUDEPY, Py_ENABLE_SHARED,
		 python_MACOSX_DEPLOYMENT_TARGET) = \
			conf.get_python_variables(python, ["get_config_var('%s')" % x for x in v],
					      ['from distutils.sysconfig import get_config_var'])
	except RuntimeError:
		conf.fatal("Python development headers not found (-v for details).")

	conf.to_log("""Configuration returned from %r:
python_prefix = %r
python_SO = %r
python_SYSLIBS = %r
python_LDFLAGS = %r
python_SHLIBS = %r
python_LIBDIR = %r
python_LIBPL = %r
INCLUDEPY = %r
Py_ENABLE_SHARED = %r
MACOSX_DEPLOYMENT_TARGET = %r
""" % (python, python_prefix, python_SO, python_SYSLIBS, python_LDFLAGS, python_SHLIBS,
	python_LIBDIR, python_LIBPL, INCLUDEPY, Py_ENABLE_SHARED, python_MACOSX_DEPLOYMENT_TARGET))

	if python_MACOSX_DEPLOYMENT_TARGET:
		conf.env['MACOSX_DEPLOYMENT_TARGET'] = python_MACOSX_DEPLOYMENT_TARGET
		conf.environ['MACOSX_DEPLOYMENT_TARGET'] = python_MACOSX_DEPLOYMENT_TARGET

	env['pyext_PATTERN'] = '%s'+python_SO

	# Check for python libraries for embedding
	if python_SYSLIBS is not None:
		for lib in python_SYSLIBS.split():
			if lib.startswith('-l'):
				lib = lib[2:] # strip '-l'
			env.append_value('LIB_PYEMBED', [lib])
	if python_SHLIBS is not None:
		for lib in python_SHLIBS.split():
			if lib.startswith('-l'):
				lib = lib[2:] # strip '-l'
			env.append_value('LIB_PYEMBED', [lib])

	if Options.platform != 'darwin' and python_LDFLAGS:
		env.append_value('LINKFLAGS_PYEMBED', python_LDFLAGS.split())

	result = False
	name = 'python' + env['PYTHON_VERSION']

	if python_LIBDIR is not None:
		path = [python_LIBDIR]
		conf.to_log("\n\n# Trying LIBDIR: %r\n" % path)
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path)

	if not result and python_LIBPL is not None:
		conf.to_log("\n\n# try again with -L$python_LIBPL (some systems don't install the python library in $prefix/lib)\n")
		path = [python_LIBPL]
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path)

	if not result:
		conf.to_log("\n\n# try again with -L$prefix/libs, and pythonXY name rather than pythonX.Y (win32)\n")
		path = [os.path.join(python_prefix, "libs")]
		name = 'python' + env['PYTHON_VERSION'].replace('.', '')
		result = conf.check(lib=name, uselib='PYEMBED', libpath=path)

	if result:
		env['LIBPATH_PYEMBED'] = path
		env.append_value('LIB_PYEMBED', [name])
	else:
		conf.to_log("\n\n### LIB NOT FOUND\n")

	# under certain conditions, python extensions must link to
	# python libraries, not just python embedding programs.
	if (sys.platform == 'win32' or sys.platform.startswith('os2')
		or sys.platform == 'darwin' or Py_ENABLE_SHARED):
		env['LIBPATH_PYEXT'] = env['LIBPATH_PYEMBED']
		env['LIB_PYEXT'] = env['LIB_PYEMBED']

	# We check that pythonX.Y-config exists, and if it exists we
	# use it to get only the includes, else fall back to distutils.
	python_config = conf.find_program(
		'python%s-config' % ('.'.join(env['PYTHON_VERSION'].split('.')[:2])),
		var='PYTHON_CONFIG')
	if not python_config:
		python_config = conf.find_program(
			'python-config-%s' % ('.'.join(env['PYTHON_VERSION'].split('.')[:2])),
			var='PYTHON_CONFIG')

	includes = []
	if python_config:
		for incstr in conf.cmd_and_log("%s %s --includes" % (python, python_config)).strip().split():
			# strip the -I or /I
			if (incstr.startswith('-I') or incstr.startswith('/I')):
				incstr = incstr[2:]
			# append include path, unless already given
			if incstr not in includes:
				includes.append(incstr)
		conf.to_log("Include path for Python extensions "
			       "(found via python-config --includes): %r\n" % (includes,))
		env['INCLUDES_PYEXT'] = includes
		env['INCLUDES_PYEMBED'] = includes
	else:
		conf.to_log("Include path for Python extensions "
			       "(found via distutils module): %r\n" % (INCLUDEPY,))
		env['INCLUDES_PYEXT'] = [INCLUDEPY]
		env['INCLUDES_PYEMBED'] = [INCLUDEPY]

	# Code using the Python API needs to be compiled with -fno-strict-aliasing
	if env['CC_NAME'] == 'gcc':
		env.append_value('CCFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CCFLAGS_PYEXT', ['-fno-strict-aliasing'])
	if env['CXX_NAME'] == 'gcc':
		env.append_value('CXXFLAGS_PYEMBED', ['-fno-strict-aliasing'])
		env.append_value('CXXFLAGS_PYEXT', ['-fno-strict-aliasing'])

	# See if it compiles
	conf.check(header_name='Python.h', define_name='HAVE_PYTHON_H',
		   uselib='PYEMBED', fragment=FRAG,
		   errmsg='Could not find the python development headers')