def setup_environment(layout):
    os.environ['PATH'] = os.pathsep.join([os.path.join(layout['bin']), os.environ['PATH']])
    os.environ['PYTHONPATH'] = os.path.join(layout['python'])
    os.environ['QTDIR'] = os.path.join(layout['root'])
    os.environ['QT_PLUGIN_PATH'] = os.path.join(layout['plugins'])
    os.environ['QT_PYQT_SDK_SETUP_DONE'] = '1'

    if sys.platform == 'linux2':
        os.environ['LD_LIBRARY_PATH'] = layout['lib']
    elif sys.platform == 'darwin':
        os.environ['DYLD_FRAMEWORK_PATH'] = layout['lib']
        os.environ['DYLD_LIBRARY_PATH'] = layout['lib']
    elif sys.platform == 'win32':
        # Setup Visual C++ 2008 environment variables.
        from distutils.msvccompiler import MSVCCompiler
        msvc = MSVCCompiler()
        msvc.initialize()

        os.environ['INCLUDE'] = os.pathsep.join([layout['include'], os.environ['INCLUDE']])
        os.environ['LIB'] = os.pathsep.join([layout['lib'], os.environ['LIB']])
        os.environ['QMAKESPEC'] = 'win32-msvc2008'

        os.environ['PATH'] = os.pathsep.join([
            os.environ['PATH'],
            # These paths must be __AFTER__ MSVC paths otherwise we pick up
            # link.exe from cygwin instead of MSVC's linker.
            layout['lib'],
            os.path.expandvars(r'%SYSTEMDRIVE%\cygwin64\bin'),
            os.path.expandvars(r'%SYSTEMDRIVE%\Perl64\bin'),
            os.path.expandvars(r'%SYSTEMDRIVE%\Python27'),
            os.path.expandvars(r'%SYSTEMDRIVE%\Ruby193\bin'),
        ])
Esempio n. 2
0
    def link (self,*arg,**kargs):
		#Generate .lib file if not yet done
        self.announce("Microsoft Visual C requires eclipse.lib\n Building it") 
        bits, linkage= platform.architecture()
        if bits=="32bit":
            machine_option="/MACHINE:X86"
        elif bits=="64bit":
            machine_option="/MACHINE:X64"
        else:
            raise "Architecture not supported"
        lib_cmd=self.find_exe('lib.exe')
        option="/def:" + os.path.join(eclipse_lib_path,"eclipse.def")
        self.spawn([lib_cmd,machine_option,option])
        oldMSVCCompiler.link(self,*arg,**kargs)
Esempio n. 3
0
    def initialize(self):
        # The 'lib' and 'include' variables may be overwritten
        # by MSVCCompiler.initialize, so save them for later merge.
        environ_lib = os.getenv('lib', '')
        environ_include = os.getenv('include', '')
        _MSVCCompiler.initialize(self)

        # Merge current and previous values of 'lib' and 'include'
        os.environ['lib'] = _merge(environ_lib, os.environ['lib'])
        os.environ['include'] = _merge(environ_include, os.environ['include'])

        # msvc9 building for 32 bits requires SSE2 to work around a
        # compiler bug.
        if platform_bits == 32:
            self.compile_options += ['/arch:SSE2']
            self.compile_options_debug += ['/arch:SSE2']
Esempio n. 4
0
def compiled_dylib(tmpdir):
    tmp_data_dir = _data_dir_copy('ctypes_dylib', tmpdir)

    # Compile the ctypes_dylib in the tmpdir: Make tmpdir/data the CWD. Don't
    # use monkeypatch.chdir to change, then monkeypatch.undo() to restore the
    # CWD, since this will undo ALL monkeypatches (such as the pyi_builder's
    # additions to sys.path), breaking the test.
    old_wd = tmp_data_dir.chdir()
    try:
        if is_win:
            tmp_data_dir = tmp_data_dir.join('ctypes_dylib.dll')
            # For Mingw-x64 we must pass '-m32' to build 32-bit binaries
            march = '-m32' if architecture() == '32bit' else '-m64'
            ret = subprocess.call('gcc -shared ' + march + ' ctypes_dylib.c -o ctypes_dylib.dll', shell=True)
            if ret != 0:
                # Find path to cl.exe file.
                from distutils.msvccompiler import MSVCCompiler
                comp = MSVCCompiler()
                comp.initialize()
                cl_path = comp.cc
                # Fallback to msvc.
                ret = subprocess.call([cl_path, '/LD', 'ctypes_dylib.c'], shell=False)
        elif is_darwin:
            tmp_data_dir = tmp_data_dir.join('ctypes_dylib.dylib')
            # On Mac OS X we need to detect architecture - 32 bit or 64 bit.
            arch = 'i386' if architecture() == '32bit' else 'x86_64'
            cmd = ('gcc -arch ' + arch + ' -Wall -dynamiclib '
                'ctypes_dylib.c -o ctypes_dylib.dylib -headerpad_max_install_names')
            ret = subprocess.call(cmd, shell=True)
            id_dylib = os.path.abspath('ctypes_dylib.dylib')
            ret = subprocess.call('install_name_tool -id %s ctypes_dylib.dylib' % (id_dylib,), shell=True)
        else:
            tmp_data_dir = tmp_data_dir.join('ctypes_dylib.so')
            ret = subprocess.call('gcc -fPIC -shared ctypes_dylib.c -o ctypes_dylib.so', shell=True)
        assert ret == 0, 'Compile ctypes_dylib failed.'
    finally:
        # Reset the CWD directory.
        old_wd.chdir()

    return tmp_data_dir
Esempio n. 5
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')
Esempio n. 6
0
 def __init__(self, verbose=0, dry_run=0, force=0):
     _MSVCCompiler.__init__(self, verbose, dry_run, force)
Esempio n. 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=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!')
Esempio n. 8
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!')
Esempio n. 9
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",
        )
Esempio n. 10
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')
Esempio n. 11
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!",
    )
Esempio n. 12
0
 def __init__(self, verbose=0, dry_run=0, force=0):
     _MSVCCompiler.__init__(self, verbose, dry_run, force)
Esempio n. 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 = 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!'
    )
Esempio n. 14
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')
Esempio n. 15
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'.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']

	# TODO simplify this
	for name in ('python' + env['PYTHON_VERSION'], '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')