blob: f6e5d999095a0ba38561db3c82319c12345e3105 [file] [log] [blame]
Fred Drake70b014d2001-07-18 18:39:56 +00001"""Provide access to Python's configuration information. The specific
2configuration variables available depend heavily on the platform and
3configuration. The values may be retrieved using
4get_config_var(name), and the list of variables is available via
5get_config_vars().keys(). Additional convenience functions are also
6available.
Greg Ward1190ee31998-12-18 23:46:33 +00007
8Written by: Fred L. Drake, Jr.
9Email: <fdrake@acm.org>
Greg Ward1190ee31998-12-18 23:46:33 +000010"""
11
Greg Ward9ddaaa11999-01-06 14:46:06 +000012import os
13import re
Tarek Ziadé36797272010-07-22 12:50:05 +000014import sys
Greg Ward1190ee31998-12-18 23:46:33 +000015
Tarek Ziadé36797272010-07-22 12:50:05 +000016from .errors import DistutilsPlatformError
Greg Warda0ca3f22000-02-02 00:05:14 +000017
Tarek Ziadé36797272010-07-22 12:50:05 +000018# These are needed in a couple of spots, so just compute them once.
19PREFIX = os.path.normpath(sys.prefix)
20EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010021BASE_PREFIX = os.path.normpath(sys.base_prefix)
22BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
Fred Drakec1ee39a2000-03-09 15:54:52 +000023
Tarek Ziadé36797272010-07-22 12:50:05 +000024# Path to the base directory of the project. On Windows the binary may
25# live in project/PCBuild9. If we're dealing with an x64 Windows build,
26# it'll live in project/PCbuild/amd64.
27project_base = os.path.dirname(os.path.abspath(sys.executable))
28if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
29 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
30# PC/VS7.1
31if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
32 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
33 os.path.pardir))
34# PC/AMD64
35if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
36 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
37 os.path.pardir))
Tarek Ziadé8b441d02010-01-29 11:46:31 +000038
Tarek Ziadé36797272010-07-22 12:50:05 +000039# python_build: (Boolean) if true, we're either building Python or
40# building an extension with an un-installed Python, so we use
41# different (hard-wired) directories.
42# Setup.local is available for Makefile builds including VPATH builds,
43# Setup.dist is available on Windows
Vinay Sajip7ded1f02012-05-26 03:45:29 +010044def _is_python_source_dir(d):
Tarek Ziadé36797272010-07-22 12:50:05 +000045 for fn in ("Setup.dist", "Setup.local"):
Vinay Sajip7ded1f02012-05-26 03:45:29 +010046 if os.path.isfile(os.path.join(d, "Modules", fn)):
Tarek Ziadé36797272010-07-22 12:50:05 +000047 return True
48 return False
Vinay Sajip7ded1f02012-05-26 03:45:29 +010049_sys_home = getattr(sys, '_home', None)
Vinay Sajip42211422012-05-26 20:36:12 +010050if _sys_home and os.name == 'nt' and \
51 _sys_home.lower().endswith(('pcbuild', 'pcbuild\\amd64')):
Vinay Sajip7ded1f02012-05-26 03:45:29 +010052 _sys_home = os.path.dirname(_sys_home)
Vinay Sajip7e203492012-05-27 17:30:09 +010053 if _sys_home.endswith('pcbuild'): # must be amd64
54 _sys_home = os.path.dirname(_sys_home)
Vinay Sajip7ded1f02012-05-26 03:45:29 +010055def _python_build():
56 if _sys_home:
57 return _is_python_source_dir(_sys_home)
58 return _is_python_source_dir(project_base)
Christian Heimes2202f872008-02-06 14:31:34 +000059python_build = _python_build()
Fred Drakec916cdc2001-08-02 20:03:12 +000060
Barry Warsaw14d98ac2010-11-24 19:43:47 +000061# Calculate the build qualifier flags if they are defined. Adding the flags
62# to the include and lib directories only makes sense for an installation, not
63# an in-source build.
64build_flags = ''
65try:
66 if not python_build:
67 build_flags = sys.abiflags
68except AttributeError:
69 # It's not a configure-based build, so the sys module doesn't have
70 # this attribute, which is fine.
71 pass
72
Tarek Ziadé36797272010-07-22 12:50:05 +000073def get_python_version():
74 """Return a string containing the major and minor Python version,
75 leaving off the patchlevel. Sample return values could be '1.5'
76 or '2.2'.
77 """
78 return sys.version[:3]
Tarek Ziadéedacea32010-01-29 11:41:03 +000079
Tarek Ziadé36797272010-07-22 12:50:05 +000080
81def get_python_inc(plat_specific=0, prefix=None):
82 """Return the directory containing installed Python header files.
Fred Drakec1ee39a2000-03-09 15:54:52 +000083
84 If 'plat_specific' is false (the default), this is the path to the
85 non-platform-specific header files, i.e. Python.h and so on;
86 otherwise, this is the path to platform-specific header files
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +000087 (namely pyconfig.h).
Fred Drakec1ee39a2000-03-09 15:54:52 +000088
Vinay Sajip7ded1f02012-05-26 03:45:29 +010089 If 'prefix' is supplied, use it instead of sys.base_prefix or
90 sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
Fred Drakeb94b8492001-12-06 20:51:35 +000091 """
Tarek Ziadé36797272010-07-22 12:50:05 +000092 if prefix is None:
Vinay Sajip7ded1f02012-05-26 03:45:29 +010093 prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
Tarek Ziadé36797272010-07-22 12:50:05 +000094 if os.name == "posix":
95 if python_build:
Vinay Sajipae7d7fa2010-09-20 10:29:54 +000096 # Assume the executable is in the build directory. The
97 # pyconfig.h file should be in the same directory. Since
98 # the build directory may not be the source directory, we
99 # must use "srcdir" from the makefile to find the "Include"
100 # directory.
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100101 base = _sys_home or os.path.dirname(os.path.abspath(sys.executable))
Vinay Sajipae7d7fa2010-09-20 10:29:54 +0000102 if plat_specific:
103 return base
104 else:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100105 incdir = os.path.join(_sys_home or get_config_var('srcdir'),
106 'Include')
Vinay Sajipae7d7fa2010-09-20 10:29:54 +0000107 return os.path.normpath(incdir)
Barry Warsaw14d98ac2010-11-24 19:43:47 +0000108 python_dir = 'python' + get_python_version() + build_flags
109 return os.path.join(prefix, "include", python_dir)
Tarek Ziadé36797272010-07-22 12:50:05 +0000110 elif os.name == "nt":
111 return os.path.join(prefix, "include")
Tarek Ziadé36797272010-07-22 12:50:05 +0000112 elif os.name == "os2":
113 return os.path.join(prefix, "Include")
Greg Ward7d73b9e2000-03-09 03:16:05 +0000114 else:
Tarek Ziadé36797272010-07-22 12:50:05 +0000115 raise DistutilsPlatformError(
116 "I don't know where Python installs its C header files "
117 "on platform '%s'" % os.name)
Greg Ward7d73b9e2000-03-09 03:16:05 +0000118
119
Tarek Ziadé36797272010-07-22 12:50:05 +0000120def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
121 """Return the directory containing the Python library (standard or
Fred Drakec1ee39a2000-03-09 15:54:52 +0000122 site additions).
Greg Ward7d73b9e2000-03-09 03:16:05 +0000123
Fred Drakec1ee39a2000-03-09 15:54:52 +0000124 If 'plat_specific' is true, return the directory containing
125 platform-specific modules, i.e. any module from a non-pure-Python
126 module distribution; otherwise, return the platform-shared library
127 directory. If 'standard_lib' is true, return the directory
128 containing standard Python library modules; otherwise, return the
129 directory for site-specific modules.
130
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100131 If 'prefix' is supplied, use it instead of sys.base_prefix or
132 sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
Fred Drakec1ee39a2000-03-09 15:54:52 +0000133 """
Tarek Ziadé36797272010-07-22 12:50:05 +0000134 if prefix is None:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100135 if standard_lib:
136 prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
137 else:
138 prefix = plat_specific and EXEC_PREFIX or PREFIX
Tarek Ziadé36797272010-07-22 12:50:05 +0000139
140 if os.name == "posix":
141 libpython = os.path.join(prefix,
142 "lib", "python" + get_python_version())
143 if standard_lib:
144 return libpython
Greg Ward7d73b9e2000-03-09 03:16:05 +0000145 else:
Tarek Ziadé36797272010-07-22 12:50:05 +0000146 return os.path.join(libpython, "site-packages")
147 elif os.name == "nt":
148 if standard_lib:
149 return os.path.join(prefix, "Lib")
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000150 else:
Tarek Ziadé36797272010-07-22 12:50:05 +0000151 if get_python_version() < "2.2":
152 return prefix
153 else:
154 return os.path.join(prefix, "Lib", "site-packages")
Tarek Ziadé36797272010-07-22 12:50:05 +0000155 elif os.name == "os2":
156 if standard_lib:
157 return os.path.join(prefix, "Lib")
158 else:
159 return os.path.join(prefix, "Lib", "site-packages")
Greg Ward7d73b9e2000-03-09 03:16:05 +0000160 else:
Tarek Ziadé36797272010-07-22 12:50:05 +0000161 raise DistutilsPlatformError(
162 "I don't know where Python installs its library "
163 "on platform '%s'" % os.name)
164
Ned Deilycbfb9a52012-06-23 16:02:19 -0700165
Tarek Ziadé36797272010-07-22 12:50:05 +0000166
167def customize_compiler(compiler):
168 """Do any platform-specific customization of a CCompiler instance.
169
170 Mainly needed on Unix, so we can plug in the information that
171 varies across Unices and is stored in Python's Makefile.
172 """
173 if compiler.compiler_type == "unix":
174 (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
175 get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
176 'CCSHARED', 'LDSHARED', 'SO', 'AR', 'ARFLAGS')
177
Ned Deily99377482012-02-10 13:01:08 +0100178 newcc = None
Tarek Ziadé36797272010-07-22 12:50:05 +0000179 if 'CC' in os.environ:
Ned Deilycbfb9a52012-06-23 16:02:19 -0700180 cc = os.environ['CC']
Tarek Ziadé36797272010-07-22 12:50:05 +0000181 if 'CXX' in os.environ:
182 cxx = os.environ['CXX']
183 if 'LDSHARED' in os.environ:
184 ldshared = os.environ['LDSHARED']
185 if 'CPP' in os.environ:
186 cpp = os.environ['CPP']
Andrew M. Kuchling29c86232002-11-04 19:53:24 +0000187 else:
Tarek Ziadé36797272010-07-22 12:50:05 +0000188 cpp = cc + " -E" # not always
189 if 'LDFLAGS' in os.environ:
190 ldshared = ldshared + ' ' + os.environ['LDFLAGS']
191 if 'CFLAGS' in os.environ:
192 cflags = opt + ' ' + os.environ['CFLAGS']
193 ldshared = ldshared + ' ' + os.environ['CFLAGS']
194 if 'CPPFLAGS' in os.environ:
195 cpp = cpp + ' ' + os.environ['CPPFLAGS']
196 cflags = cflags + ' ' + os.environ['CPPFLAGS']
197 ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
198 if 'AR' in os.environ:
199 ar = os.environ['AR']
200 if 'ARFLAGS' in os.environ:
201 archiver = ar + ' ' + os.environ['ARFLAGS']
202 else:
203 archiver = ar + ' ' + ar_flags
204
205 cc_cmd = cc + ' ' + cflags
206 compiler.set_executables(
207 preprocessor=cpp,
208 compiler=cc_cmd,
209 compiler_so=cc_cmd + ' ' + ccshared,
210 compiler_cxx=cxx,
211 linker_so=ldshared,
212 linker_exe=cc,
213 archiver=archiver)
214
215 compiler.shared_lib_extension = so_ext
216
217
218def get_config_h_filename():
219 """Return full pathname of installed pyconfig.h file."""
220 if python_build:
221 if os.name == "nt":
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100222 inc_dir = os.path.join(_sys_home or project_base, "PC")
Tarek Ziadé36797272010-07-22 12:50:05 +0000223 else:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100224 inc_dir = _sys_home or project_base
Tarek Ziadé36797272010-07-22 12:50:05 +0000225 else:
226 inc_dir = get_python_inc(plat_specific=1)
227 if get_python_version() < '2.2':
228 config_h = 'config.h'
229 else:
230 # The name of the config.h file changed in 2.2
231 config_h = 'pyconfig.h'
232 return os.path.join(inc_dir, config_h)
233
Greg Ward1190ee31998-12-18 23:46:33 +0000234
Greg Ward9ddaaa11999-01-06 14:46:06 +0000235def get_makefile_filename():
Tarek Ziadé36797272010-07-22 12:50:05 +0000236 """Return full pathname of installed Makefile from the Python build."""
237 if python_build:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100238 return os.path.join(_sys_home or os.path.dirname(sys.executable),
239 "Makefile")
Éric Araujofea2d042011-10-08 01:56:52 +0200240 lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
Barry Warsaw14d98ac2010-11-24 19:43:47 +0000241 config_file = 'config-{}{}'.format(get_python_version(), build_flags)
242 return os.path.join(lib_dir, config_file, 'Makefile')
Greg Ward7d73b9e2000-03-09 03:16:05 +0000243
Tarek Ziadé36797272010-07-22 12:50:05 +0000244
245def parse_config_h(fp, g=None):
246 """Parse a config.h-style file.
247
248 A dictionary containing name/value pairs is returned. If an
249 optional dictionary is passed in as the second argument, it is
250 used instead of a new dictionary.
Fred Drake522af3a1999-01-06 16:28:34 +0000251 """
Tarek Ziadé36797272010-07-22 12:50:05 +0000252 if g is None:
253 g = {}
254 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
255 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
256 #
257 while True:
258 line = fp.readline()
259 if not line:
260 break
261 m = define_rx.match(line)
262 if m:
263 n, v = m.group(1, 2)
264 try: v = int(v)
265 except ValueError: pass
266 g[n] = v
267 else:
268 m = undef_rx.match(line)
269 if m:
270 g[m.group(1)] = 0
271 return g
Greg Ward1190ee31998-12-18 23:46:33 +0000272
Greg Wardd283ce72000-09-17 00:53:02 +0000273
274# Regexes needed for parsing Makefile (and similar syntaxes,
275# like old-style Setup files).
276_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
277_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
278_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
279
Greg Ward3fff8d22000-09-15 00:03:13 +0000280def parse_makefile(fn, g=None):
Tarek Ziadé36797272010-07-22 12:50:05 +0000281 """Parse a Makefile-style file.
Fred Drakec1ee39a2000-03-09 15:54:52 +0000282
283 A dictionary containing name/value pairs is returned. If an
284 optional dictionary is passed in as the second argument, it is
285 used instead of a new dictionary.
Fred Drake522af3a1999-01-06 16:28:34 +0000286 """
Tarek Ziadé36797272010-07-22 12:50:05 +0000287 from distutils.text_file import TextFile
Victor Stinner75d8c5c2010-10-23 17:02:31 +0000288 fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
Tarek Ziadé36797272010-07-22 12:50:05 +0000289
290 if g is None:
291 g = {}
292 done = {}
293 notdone = {}
294
295 while True:
296 line = fp.readline()
297 if line is None: # eof
298 break
299 m = _variable_rx.match(line)
300 if m:
301 n, v = m.group(1, 2)
302 v = v.strip()
303 # `$$' is a literal `$' in make
304 tmpv = v.replace('$$', '')
305
306 if "$" in tmpv:
307 notdone[n] = v
308 else:
309 try:
310 v = int(v)
311 except ValueError:
312 # insert literal `$'
313 done[n] = v.replace('$$', '$')
314 else:
315 done[n] = v
316
Ronald Oussorene8d252d2010-07-23 09:43:17 +0000317 # Variables with a 'PY_' prefix in the makefile. These need to
318 # be made available without that prefix through sysconfig.
319 # Special care is needed to ensure that variable expansion works, even
320 # if the expansion uses the name without a prefix.
321 renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
322
Tarek Ziadé36797272010-07-22 12:50:05 +0000323 # do variable interpolation here
324 while notdone:
325 for name in list(notdone):
326 value = notdone[name]
327 m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
328 if m:
329 n = m.group(1)
330 found = True
331 if n in done:
332 item = str(done[n])
333 elif n in notdone:
334 # get it on a subsequent round
335 found = False
336 elif n in os.environ:
337 # do it like make: fall back to environment
338 item = os.environ[n]
Ronald Oussorene8d252d2010-07-23 09:43:17 +0000339
340 elif n in renamed_variables:
341 if name.startswith('PY_') and name[3:] in renamed_variables:
342 item = ""
343
344 elif 'PY_' + n in notdone:
345 found = False
346
347 else:
348 item = str(done['PY_' + n])
Tarek Ziadé36797272010-07-22 12:50:05 +0000349 else:
350 done[n] = item = ""
351 if found:
352 after = value[m.end():]
353 value = value[:m.start()] + item + after
354 if "$" in after:
355 notdone[name] = value
356 else:
357 try: value = int(value)
358 except ValueError:
359 done[name] = value.strip()
360 else:
361 done[name] = value
362 del notdone[name]
Ronald Oussorene8d252d2010-07-23 09:43:17 +0000363
364 if name.startswith('PY_') \
365 and name[3:] in renamed_variables:
366
367 name = name[3:]
368 if name not in done:
369 done[name] = value
Tarek Ziadé36797272010-07-22 12:50:05 +0000370 else:
371 # bogus variable reference; just drop it since we can't deal
372 del notdone[name]
373
374 fp.close()
375
Antoine Pitroudbec7802010-10-10 09:37:12 +0000376 # strip spurious spaces
377 for k, v in done.items():
378 if isinstance(v, str):
379 done[k] = v.strip()
380
Tarek Ziadé36797272010-07-22 12:50:05 +0000381 # save the results in the global dictionary
382 g.update(done)
383 return g
384
Greg Ward1190ee31998-12-18 23:46:33 +0000385
Greg Wardd283ce72000-09-17 00:53:02 +0000386def expand_makefile_vars(s, vars):
Tarek Ziadé36797272010-07-22 12:50:05 +0000387 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
Greg Wardd283ce72000-09-17 00:53:02 +0000388 'string' according to 'vars' (a dictionary mapping variable names to
389 values). Variables not present in 'vars' are silently expanded to the
390 empty string. The variable values in 'vars' should not contain further
391 variable expansions; if 'vars' is the output of 'parse_makefile()',
392 you're fine. Returns a variable-expanded version of 's'.
393 """
394
395 # This algorithm does multiple expansion, so if vars['foo'] contains
396 # "${bar}", it will expand ${foo} to ${bar}, and then expand
397 # ${bar}... and so forth. This is fine as long as 'vars' comes from
398 # 'parse_makefile()', which takes care of such expansions eagerly,
399 # according to make's variable expansion semantics.
400
Collin Winter5b7e9d72007-08-30 03:52:21 +0000401 while True:
Greg Wardd283ce72000-09-17 00:53:02 +0000402 m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
403 if m:
Greg Wardd283ce72000-09-17 00:53:02 +0000404 (beg, end) = m.span()
405 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
406 else:
407 break
408 return s
Tarek Ziadé36797272010-07-22 12:50:05 +0000409
410
411_config_vars = None
412
413def _init_posix():
414 """Initialize the module as appropriate for POSIX systems."""
415 g = {}
416 # load the installed Makefile:
417 try:
418 filename = get_makefile_filename()
419 parse_makefile(filename, g)
420 except IOError as msg:
421 my_msg = "invalid Python installation: unable to open %s" % filename
422 if hasattr(msg, "strerror"):
423 my_msg = my_msg + " (%s)" % msg.strerror
424
425 raise DistutilsPlatformError(my_msg)
426
427 # load the installed pyconfig.h:
428 try:
429 filename = get_config_h_filename()
Brett Cannon5c035c02010-10-29 22:36:08 +0000430 with open(filename) as file:
431 parse_config_h(file, g)
Tarek Ziadé36797272010-07-22 12:50:05 +0000432 except IOError as msg:
433 my_msg = "invalid Python installation: unable to open %s" % filename
434 if hasattr(msg, "strerror"):
435 my_msg = my_msg + " (%s)" % msg.strerror
436
437 raise DistutilsPlatformError(my_msg)
438
Tarek Ziadé36797272010-07-22 12:50:05 +0000439 # On AIX, there are wrong paths to the linker scripts in the Makefile
440 # -- these paths are relative to the Python source, but when installed
441 # the scripts are in another directory.
442 if python_build:
443 g['LDSHARED'] = g['BLDSHARED']
444
445 elif get_python_version() < '2.1':
446 # The following two branches are for 1.5.2 compatibility.
447 if sys.platform == 'aix4': # what about AIX 3.x ?
448 # Linker script is in the config directory, not in Modules as the
449 # Makefile says.
450 python_lib = get_python_lib(standard_lib=1)
451 ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
452 python_exp = os.path.join(python_lib, 'config', 'python.exp')
453
454 g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
455
456 global _config_vars
457 _config_vars = g
458
459
460def _init_nt():
461 """Initialize the module as appropriate for NT"""
462 g = {}
463 # set basic install directories
464 g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
465 g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
466
467 # XXX hmmm.. a normal install puts include files here
468 g['INCLUDEPY'] = get_python_inc(plat_specific=0)
469
470 g['SO'] = '.pyd'
471 g['EXE'] = ".exe"
472 g['VERSION'] = get_python_version().replace(".", "")
473 g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
474
475 global _config_vars
476 _config_vars = g
477
478
Tarek Ziadé36797272010-07-22 12:50:05 +0000479def _init_os2():
480 """Initialize the module as appropriate for OS/2"""
481 g = {}
482 # set basic install directories
483 g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
484 g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
485
486 # XXX hmmm.. a normal install puts include files here
487 g['INCLUDEPY'] = get_python_inc(plat_specific=0)
488
489 g['SO'] = '.pyd'
490 g['EXE'] = ".exe"
491
492 global _config_vars
493 _config_vars = g
494
495
Ned Deilycbfb9a52012-06-23 16:02:19 -0700496def _read_output(commandstring):
497 """
498 Returns os.popen(commandstring, "r").read(), but
499 without actually using os.popen because that
500 function is not usable during python bootstrap
501 """
502 # NOTE: tempfile is also not useable during
503 # bootstrap
504 import contextlib
505 try:
506 import tempfile
507 fp = tempfile.NamedTemporaryFile()
508 except ImportError:
509 fp = open("/tmp/distutils.%s"%(
510 os.getpid(),), "w+b")
511
512 with contextlib.closing(fp) as fp:
513 cmd = "%s >'%s'"%(commandstring, fp.name)
514 os.system(cmd)
515 data = fp.read()
516
517 return data.decode('utf-8')
518
Tarek Ziadé36797272010-07-22 12:50:05 +0000519def get_config_vars(*args):
520 """With no arguments, return a dictionary of all configuration
521 variables relevant for the current platform. Generally this includes
522 everything needed to build extensions and install both pure modules and
523 extensions. On Unix, this means every variable defined in Python's
524 installed Makefile; on Windows and Mac OS it's a much smaller set.
525
526 With arguments, return a list of values that result from looking up
527 each argument in the configuration variable dictionary.
528 """
529 global _config_vars
530 if _config_vars is None:
531 func = globals().get("_init_" + os.name)
532 if func:
533 func()
534 else:
535 _config_vars = {}
536
537 # Normalized versions of prefix and exec_prefix are handy to have;
538 # in fact, these are the standard versions used most places in the
539 # Distutils.
540 _config_vars['prefix'] = PREFIX
541 _config_vars['exec_prefix'] = EXEC_PREFIX
542
543 # Convert srcdir into an absolute path if it appears necessary.
544 # Normally it is relative to the build directory. However, during
545 # testing, for example, we might be running a non-installed python
546 # from a different directory.
547 if python_build and os.name == "posix":
548 base = os.path.dirname(os.path.abspath(sys.executable))
549 if (not os.path.isabs(_config_vars['srcdir']) and
550 base != os.getcwd()):
551 # srcdir is relative and we are not in the same directory
552 # as the executable. Assume executable is in the build
553 # directory and make srcdir absolute.
554 srcdir = os.path.join(base, _config_vars['srcdir'])
555 _config_vars['srcdir'] = os.path.normpath(srcdir)
556
557 if sys.platform == 'darwin':
Ned Deilycbfb9a52012-06-23 16:02:19 -0700558 from distutils.spawn import find_executable
559
Tarek Ziadé36797272010-07-22 12:50:05 +0000560 kernel_version = os.uname()[2] # Kernel version (8.4.3)
561 major_version = int(kernel_version.split('.')[0])
562
Ned Deilycbfb9a52012-06-23 16:02:19 -0700563 # Issue #13590:
564 # The OSX location for the compiler varies between OSX
565 # (or rather Xcode) releases. With older releases (up-to 10.5)
566 # the compiler is in /usr/bin, with newer releases the compiler
567 # can only be found inside Xcode.app if the "Command Line Tools"
568 # are not installed.
569 #
570 # Futhermore, the compiler that can be used varies between
571 # Xcode releases. Upto Xcode 4 it was possible to use 'gcc-4.2'
572 # as the compiler, after that 'clang' should be used because
573 # gcc-4.2 is either not present, or a copy of 'llvm-gcc' that
574 # miscompiles Python.
575
576 # skip checks if the compiler was overriden with a CC env variable
577 if 'CC' not in os.environ:
578 cc = oldcc = _config_vars['CC']
579 if not find_executable(cc):
580 # Compiler is not found on the shell search PATH.
581 # Now search for clang, first on PATH (if the Command LIne
582 # Tools have been installed in / or if the user has provided
583 # another location via CC). If not found, try using xcrun
584 # to find an uninstalled clang (within a selected Xcode).
585
586 # NOTE: Cannot use subprocess here because of bootstrap
587 # issues when building Python itself (and os.popen is
588 # implemented on top of subprocess and is therefore not
589 # usable as well)
590
591 data = (find_executable('clang') or
592 _read_output(
593 "/usr/bin/xcrun -find clang 2>/dev/null").strip())
594 if not data:
595 raise DistutilsPlatformError(
596 "Cannot locate working compiler")
597
598 _config_vars['CC'] = cc = data
599 _config_vars['CXX'] = cc + '++'
600
601 elif os.path.basename(cc).startswith('gcc'):
602 # Compiler is GCC, check if it is LLVM-GCC
603 data = _read_output("'%s' --version 2>/dev/null"
604 % (cc.replace("'", "'\"'\"'"),))
605 if 'llvm-gcc' in data:
606 # Found LLVM-GCC, fall back to clang
607 data = (find_executable('clang') or
608 _read_output(
609 "/usr/bin/xcrun -find clang 2>/dev/null").strip())
610 if find_executable(data):
611 _config_vars['CC'] = cc = data
612 _config_vars['CXX'] = cc + '++'
613
614 if (cc != oldcc
615 and 'LDSHARED' in _config_vars
616 and 'LDSHARED' not in os.environ):
617 # modify LDSHARED if we modified CC
618 ldshared = _config_vars['LDSHARED']
619 if ldshared.startswith(oldcc):
620 _config_vars['LDSHARED'] = cc + ldshared[len(oldcc):]
621
Tarek Ziadé36797272010-07-22 12:50:05 +0000622 if major_version < 8:
623 # On Mac OS X before 10.4, check if -arch and -isysroot
624 # are in CFLAGS or LDFLAGS and remove them if they are.
625 # This is needed when building extensions on a 10.3 system
626 # using a universal build of python.
Ned Deily27471772012-07-15 21:30:03 -0700627 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
Tarek Ziadé36797272010-07-22 12:50:05 +0000628 # a number of derived variables. These need to be
629 # patched up as well.
630 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
631 flags = _config_vars[key]
632 flags = re.sub('-arch\s+\w+\s', ' ', flags, re.ASCII)
633 flags = re.sub('-isysroot [^ \t]*', ' ', flags)
634 _config_vars[key] = flags
635
636 else:
Ned Deilycbfb9a52012-06-23 16:02:19 -0700637 # Different Xcode releases support different sets for '-arch'
638 # flags. In particular, Xcode 4.x no longer supports the
639 # PPC architectures.
640 #
641 # This code automatically removes '-arch ppc' and '-arch ppc64'
642 # when these are not supported. That makes it possible to
643 # build extensions on OSX 10.7 and later with the prebuilt
644 # 32-bit installer on the python.org website.
645 flags = _config_vars['CFLAGS']
646 if re.search('-arch\s+ppc', flags) is not None:
647 # NOTE: Cannot use subprocess here because of bootstrap
648 # issues when building Python itself
649 status = os.system("'%s' -arch ppc -x c /dev/null 2>/dev/null"%(
650 _config_vars['CC'].replace("'", "'\"'\"'"),))
651
652 if status != 0:
653 # Compiler doesn't support PPC, remove the related
654 # '-arch' flags.
655 for key in ('LDFLAGS', 'BASECFLAGS',
656 # a number of derived variables. These need to be
657 # patched up as well.
658 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED', 'LDSHARED'):
659
660 flags = _config_vars[key]
661 flags = re.sub('-arch\s+ppc\w*\s', ' ', flags)
662 _config_vars[key] = flags
663
Tarek Ziadé36797272010-07-22 12:50:05 +0000664
665 # Allow the user to override the architecture flags using
666 # an environment variable.
667 # NOTE: This name was introduced by Apple in OSX 10.5 and
668 # is used by several scripting languages distributed with
669 # that OS release.
Tarek Ziadé36797272010-07-22 12:50:05 +0000670 if 'ARCHFLAGS' in os.environ:
671 arch = os.environ['ARCHFLAGS']
Ned Deily27471772012-07-15 21:30:03 -0700672 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
Tarek Ziadé36797272010-07-22 12:50:05 +0000673 # a number of derived variables. These need to be
674 # patched up as well.
Ned Deily27471772012-07-15 21:30:03 -0700675 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
Tarek Ziadé36797272010-07-22 12:50:05 +0000676
677 flags = _config_vars[key]
678 flags = re.sub('-arch\s+\w+\s', ' ', flags)
679 flags = flags + ' ' + arch
680 _config_vars[key] = flags
681
Ned Deily27471772012-07-15 21:30:03 -0700682 # If we're on OSX 10.5 or later and the user tries to
683 # compiles an extension using an SDK that is not present
684 # on the current machine it is better to not use an SDK
685 # than to fail.
686 #
687 # The major usecase for this is users using a Python.org
688 # binary installer on OSX 10.6: that installer uses
689 # the 10.4u SDK, but that SDK is not installed by default
690 # when you install Xcode.
691 #
692 m = re.search('-isysroot\s+(\S+)', _config_vars['CFLAGS'])
693 if m is not None:
694 sdk = m.group(1)
695 if not os.path.exists(sdk):
696 for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
697 # a number of derived variables. These need to be
698 # patched up as well.
699 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
700
701 flags = _config_vars[key]
702 flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
703 _config_vars[key] = flags
704
Tarek Ziadé36797272010-07-22 12:50:05 +0000705 if args:
706 vals = []
707 for name in args:
708 vals.append(_config_vars.get(name))
709 return vals
710 else:
711 return _config_vars
712
713def get_config_var(name):
714 """Return the value of a single variable using the dictionary
715 returned by 'get_config_vars()'. Equivalent to
716 get_config_vars().get(name)
717 """
718 return get_config_vars().get(name)