blob: 0c726d92ffbaddaa18d6a59833bd6108c17d6043 [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 Ward82d71ca2000-06-03 00:44:30 +000012__revision__ = "$Id$"
Greg Ward1190ee31998-12-18 23:46:33 +000013
Tarek Ziadédd7bef92010-03-05 00:16:02 +000014import os
Greg Ward9ddaaa11999-01-06 14:46:06 +000015import re
Tarek Ziadédd7bef92010-03-05 00:16:02 +000016import string
17import sys
Greg Ward1190ee31998-12-18 23:46:33 +000018
Tarek Ziadédd7bef92010-03-05 00:16:02 +000019from distutils.errors import DistutilsPlatformError
Greg Warda0ca3f22000-02-02 00:05:14 +000020
Tarek Ziadédd7bef92010-03-05 00:16:02 +000021# These are needed in a couple of spots, so just compute them once.
22PREFIX = os.path.normpath(sys.prefix)
23EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
Tarek Ziadé0276c7a2010-01-26 21:21:54 +000024
Tarek Ziadédd7bef92010-03-05 00:16:02 +000025# Path to the base directory of the project. On Windows the binary may
26# live in project/PCBuild9. If we're dealing with an x64 Windows build,
27# it'll live in project/PCbuild/amd64.
28project_base = os.path.dirname(os.path.abspath(sys.executable))
29if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
30 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
31# PC/VS7.1
32if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
33 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
34 os.path.pardir))
35# PC/AMD64
36if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
37 project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
38 os.path.pardir))
Fred Drakec1ee39a2000-03-09 15:54:52 +000039
doko@python.orgd65e2ba2013-01-31 23:52:03 +010040# set for cross builds
41if "_PYTHON_PROJECT_BASE" in os.environ:
42 # this is the build directory, at least for posix
43 project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"])
44
Tarek Ziadédd7bef92010-03-05 00:16:02 +000045# python_build: (Boolean) if true, we're either building Python or
46# building an extension with an un-installed Python, so we use
47# different (hard-wired) directories.
48# Setup.local is available for Makefile builds including VPATH builds,
49# Setup.dist is available on Windows
Marc-André Lemburg2db7cd32008-02-05 14:50:40 +000050def _python_build():
Tarek Ziadédd7bef92010-03-05 00:16:02 +000051 for fn in ("Setup.dist", "Setup.local"):
52 if os.path.isfile(os.path.join(project_base, "Modules", fn)):
53 return True
54 return False
Marc-André Lemburg2db7cd32008-02-05 14:50:40 +000055python_build = _python_build()
Fred Drakec1ee39a2000-03-09 15:54:52 +000056
Tarek Ziadé5633a802010-01-23 09:23:15 +000057
Tarek Ziadédd7bef92010-03-05 00:16:02 +000058def get_python_version():
59 """Return a string containing the major and minor Python version,
60 leaving off the patchlevel. Sample return values could be '1.5'
61 or '2.2'.
62 """
63 return sys.version[:3]
64
65
66def get_python_inc(plat_specific=0, prefix=None):
67 """Return the directory containing installed Python header files.
Fred Drakec1ee39a2000-03-09 15:54:52 +000068
69 If 'plat_specific' is false (the default), this is the path to the
70 non-platform-specific header files, i.e. Python.h and so on;
71 otherwise, this is the path to platform-specific header files
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +000072 (namely pyconfig.h).
Fred Drakec1ee39a2000-03-09 15:54:52 +000073
Greg Wardd38e6f72000-04-10 01:17:49 +000074 If 'prefix' is supplied, use it instead of sys.prefix or
75 sys.exec_prefix -- i.e., ignore 'plat_specific'.
Fred Drakeb94b8492001-12-06 20:51:35 +000076 """
Tarek Ziadédd7bef92010-03-05 00:16:02 +000077 if prefix is None:
78 prefix = plat_specific and EXEC_PREFIX or PREFIX
Tarek Ziadéa5cd1822010-04-30 12:15:12 +000079
Tarek Ziadédd7bef92010-03-05 00:16:02 +000080 if os.name == "posix":
81 if python_build:
Tarek Ziadéa5cd1822010-04-30 12:15:12 +000082 buildir = os.path.dirname(sys.executable)
Tarek Ziadédd7bef92010-03-05 00:16:02 +000083 if plat_specific:
Tarek Ziadéa5cd1822010-04-30 12:15:12 +000084 # python.h is located in the buildir
85 inc_dir = buildir
Tarek Ziadédd7bef92010-03-05 00:16:02 +000086 else:
Tarek Ziadéa5cd1822010-04-30 12:15:12 +000087 # the source dir is relative to the buildir
88 srcdir = os.path.abspath(os.path.join(buildir,
89 get_config_var('srcdir')))
90 # Include is located in the srcdir
91 inc_dir = os.path.join(srcdir, "Include")
Tarek Ziadédd7bef92010-03-05 00:16:02 +000092 return inc_dir
93 return os.path.join(prefix, "include", "python" + get_python_version())
94 elif os.name == "nt":
95 return os.path.join(prefix, "include")
Tarek Ziadédd7bef92010-03-05 00:16:02 +000096 elif os.name == "os2":
97 return os.path.join(prefix, "Include")
Greg Ward7d73b9e2000-03-09 03:16:05 +000098 else:
Tarek Ziadédd7bef92010-03-05 00:16:02 +000099 raise DistutilsPlatformError(
100 "I don't know where Python installs its C header files "
101 "on platform '%s'" % os.name)
Greg Ward7d73b9e2000-03-09 03:16:05 +0000102
103
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000104def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
105 """Return the directory containing the Python library (standard or
Fred Drakec1ee39a2000-03-09 15:54:52 +0000106 site additions).
Greg Ward7d73b9e2000-03-09 03:16:05 +0000107
Fred Drakec1ee39a2000-03-09 15:54:52 +0000108 If 'plat_specific' is true, return the directory containing
109 platform-specific modules, i.e. any module from a non-pure-Python
110 module distribution; otherwise, return the platform-shared library
111 directory. If 'standard_lib' is true, return the directory
112 containing standard Python library modules; otherwise, return the
113 directory for site-specific modules.
114
Greg Wardd38e6f72000-04-10 01:17:49 +0000115 If 'prefix' is supplied, use it instead of sys.prefix or
116 sys.exec_prefix -- i.e., ignore 'plat_specific'.
Fred Drakec1ee39a2000-03-09 15:54:52 +0000117 """
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000118 if prefix is None:
119 prefix = plat_specific and EXEC_PREFIX or PREFIX
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000120
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000121 if os.name == "posix":
122 libpython = os.path.join(prefix,
123 "lib", "python" + get_python_version())
124 if standard_lib:
125 return libpython
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000126 else:
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000127 return os.path.join(libpython, "site-packages")
128
129 elif os.name == "nt":
130 if standard_lib:
131 return os.path.join(prefix, "Lib")
132 else:
133 if get_python_version() < "2.2":
134 return prefix
135 else:
136 return os.path.join(prefix, "Lib", "site-packages")
137
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000138 elif os.name == "os2":
139 if standard_lib:
140 return os.path.join(prefix, "Lib")
141 else:
142 return os.path.join(prefix, "Lib", "site-packages")
143
Greg Ward7d73b9e2000-03-09 03:16:05 +0000144 else:
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000145 raise DistutilsPlatformError(
146 "I don't know where Python installs its library "
147 "on platform '%s'" % os.name)
148
Ned Deily18fae3f2013-01-31 01:24:55 -0800149
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000150
151def customize_compiler(compiler):
152 """Do any platform-specific customization of a CCompiler instance.
153
154 Mainly needed on Unix, so we can plug in the information that
155 varies across Unices and is stored in Python's Makefile.
156 """
157 if compiler.compiler_type == "unix":
Ned Deily18fae3f2013-01-31 01:24:55 -0800158 if sys.platform == "darwin":
159 # Perform first-time customization of compiler-related
160 # config vars on OS X now that we know we need a compiler.
161 # This is primarily to support Pythons from binary
162 # installers. The kind and paths to build tools on
163 # the user system may vary significantly from the system
164 # that Python itself was built on. Also the user OS
165 # version and build tools may not support the same set
166 # of CPU architectures for universal builds.
167 global _config_vars
168 if not _config_vars.get('CUSTOMIZED_OSX_COMPILER', ''):
169 import _osx_support
170 _osx_support.customize_compiler(_config_vars)
171 _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
172
Ned Deilyc47a4592012-02-11 20:40:24 +0100173 (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000174 get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
Ned Deilyc47a4592012-02-11 20:40:24 +0100175 'CCSHARED', 'LDSHARED', 'SO', 'AR',
176 'ARFLAGS')
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000177
Ned Deily0d0ea482012-02-10 12:59:06 +0100178 newcc = None
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000179 if 'CC' in os.environ:
Ned Deily18fae3f2013-01-31 01:24:55 -0800180 cc = os.environ['CC']
Tarek Ziadédd7bef92010-03-05 00:16:02 +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édd7bef92010-03-05 00:16:02 +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']
Ned Deilyc47a4592012-02-11 20:40:24 +0100198 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
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000204
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,
Ned Deilyc47a4592012-02-11 20:40:24 +0100212 linker_exe=cc,
213 archiver=archiver)
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000214
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":
222 inc_dir = os.path.join(project_base, "PC")
223 else:
224 inc_dir = project_base
225 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édd7bef92010-03-05 00:16:02 +0000236 """Return full pathname of installed Makefile from the Python build."""
237 if python_build:
doko@python.orgd65e2ba2013-01-31 23:52:03 +0100238 return os.path.join(project_base, "Makefile")
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000239 lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
240 return os.path.join(lib_dir, "config", "Makefile")
Greg Ward7d73b9e2000-03-09 03:16:05 +0000241
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000242
243def parse_config_h(fp, g=None):
244 """Parse a config.h-style file.
245
246 A dictionary containing name/value pairs is returned. If an
247 optional dictionary is passed in as the second argument, it is
248 used instead of a new dictionary.
Fred Drake522af3a1999-01-06 16:28:34 +0000249 """
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000250 if g is None:
251 g = {}
252 define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
253 undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
254 #
255 while 1:
256 line = fp.readline()
257 if not line:
258 break
259 m = define_rx.match(line)
260 if m:
261 n, v = m.group(1, 2)
262 try: v = int(v)
263 except ValueError: pass
264 g[n] = v
265 else:
266 m = undef_rx.match(line)
267 if m:
268 g[m.group(1)] = 0
269 return g
270
Greg Wardd283ce72000-09-17 00:53:02 +0000271
272# Regexes needed for parsing Makefile (and similar syntaxes,
273# like old-style Setup files).
274_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
275_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
276_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
277
Greg Ward3fff8d22000-09-15 00:03:13 +0000278def parse_makefile(fn, g=None):
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000279 """Parse a Makefile-style file.
Fred Drakec1ee39a2000-03-09 15:54:52 +0000280
281 A dictionary containing name/value pairs is returned. If an
282 optional dictionary is passed in as the second argument, it is
283 used instead of a new dictionary.
Fred Drake522af3a1999-01-06 16:28:34 +0000284 """
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000285 from distutils.text_file import TextFile
286 fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
287
288 if g is None:
289 g = {}
290 done = {}
291 notdone = {}
292
293 while 1:
294 line = fp.readline()
295 if line is None: # eof
296 break
297 m = _variable_rx.match(line)
298 if m:
299 n, v = m.group(1, 2)
300 v = v.strip()
301 # `$$' is a literal `$' in make
302 tmpv = v.replace('$$', '')
303
304 if "$" in tmpv:
305 notdone[n] = v
306 else:
307 try:
308 v = int(v)
309 except ValueError:
310 # insert literal `$'
311 done[n] = v.replace('$$', '$')
312 else:
313 done[n] = v
314
315 # do variable interpolation here
316 while notdone:
317 for name in notdone.keys():
318 value = notdone[name]
319 m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
320 if m:
321 n = m.group(1)
322 found = True
323 if n in done:
324 item = str(done[n])
325 elif n in notdone:
326 # get it on a subsequent round
327 found = False
328 elif n in os.environ:
329 # do it like make: fall back to environment
330 item = os.environ[n]
331 else:
332 done[n] = item = ""
333 if found:
334 after = value[m.end():]
335 value = value[:m.start()] + item + after
336 if "$" in after:
337 notdone[name] = value
338 else:
339 try: value = int(value)
340 except ValueError:
341 done[name] = value.strip()
342 else:
343 done[name] = value
344 del notdone[name]
345 else:
346 # bogus variable reference; just drop it since we can't deal
347 del notdone[name]
348
349 fp.close()
350
Antoine Pitrou58dab672010-10-10 09:54:59 +0000351 # strip spurious spaces
352 for k, v in done.items():
353 if isinstance(v, str):
354 done[k] = v.strip()
355
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000356 # save the results in the global dictionary
357 g.update(done)
358 return g
359
Greg Ward1190ee31998-12-18 23:46:33 +0000360
Greg Wardd283ce72000-09-17 00:53:02 +0000361def expand_makefile_vars(s, vars):
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000362 """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
Greg Wardd283ce72000-09-17 00:53:02 +0000363 'string' according to 'vars' (a dictionary mapping variable names to
364 values). Variables not present in 'vars' are silently expanded to the
365 empty string. The variable values in 'vars' should not contain further
366 variable expansions; if 'vars' is the output of 'parse_makefile()',
367 you're fine. Returns a variable-expanded version of 's'.
368 """
369
370 # This algorithm does multiple expansion, so if vars['foo'] contains
371 # "${bar}", it will expand ${foo} to ${bar}, and then expand
372 # ${bar}... and so forth. This is fine as long as 'vars' comes from
373 # 'parse_makefile()', which takes care of such expansions eagerly,
374 # according to make's variable expansion semantics.
375
376 while 1:
377 m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
378 if m:
Greg Wardd283ce72000-09-17 00:53:02 +0000379 (beg, end) = m.span()
380 s = s[0:beg] + vars.get(m.group(1)) + s[end:]
381 else:
382 break
383 return s
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000384
385
386_config_vars = None
387
388def _init_posix():
389 """Initialize the module as appropriate for POSIX systems."""
doko@ubuntu.com6cb43432013-04-08 21:20:09 +0200390 # _sysconfigdata is generated at build time, see the sysconfig module
391 from _sysconfigdata import build_time_vars
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000392 global _config_vars
doko@ubuntu.com6cb43432013-04-08 21:20:09 +0200393 _config_vars = {}
394 _config_vars.update(build_time_vars)
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000395
396
397def _init_nt():
398 """Initialize the module as appropriate for NT"""
399 g = {}
400 # set basic install directories
401 g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
402 g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
403
404 # XXX hmmm.. a normal install puts include files here
405 g['INCLUDEPY'] = get_python_inc(plat_specific=0)
406
407 g['SO'] = '.pyd'
408 g['EXE'] = ".exe"
409 g['VERSION'] = get_python_version().replace(".", "")
410 g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
411
412 global _config_vars
413 _config_vars = g
414
415
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000416def _init_os2():
417 """Initialize the module as appropriate for OS/2"""
418 g = {}
419 # set basic install directories
420 g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
421 g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
422
423 # XXX hmmm.. a normal install puts include files here
424 g['INCLUDEPY'] = get_python_inc(plat_specific=0)
425
426 g['SO'] = '.pyd'
427 g['EXE'] = ".exe"
428
429 global _config_vars
430 _config_vars = g
431
432
433def get_config_vars(*args):
434 """With no arguments, return a dictionary of all configuration
435 variables relevant for the current platform. Generally this includes
436 everything needed to build extensions and install both pure modules and
437 extensions. On Unix, this means every variable defined in Python's
438 installed Makefile; on Windows and Mac OS it's a much smaller set.
439
440 With arguments, return a list of values that result from looking up
441 each argument in the configuration variable dictionary.
442 """
443 global _config_vars
444 if _config_vars is None:
445 func = globals().get("_init_" + os.name)
446 if func:
447 func()
448 else:
449 _config_vars = {}
450
451 # Normalized versions of prefix and exec_prefix are handy to have;
452 # in fact, these are the standard versions used most places in the
453 # Distutils.
454 _config_vars['prefix'] = PREFIX
455 _config_vars['exec_prefix'] = EXEC_PREFIX
456
Ned Deily18fae3f2013-01-31 01:24:55 -0800457 # OS X platforms require special customization to handle
458 # multi-architecture, multi-os-version installers
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000459 if sys.platform == 'darwin':
Ned Deily18fae3f2013-01-31 01:24:55 -0800460 import _osx_support
461 _osx_support.customize_config_vars(_config_vars)
Tarek Ziadédd7bef92010-03-05 00:16:02 +0000462
463 if args:
464 vals = []
465 for name in args:
466 vals.append(_config_vars.get(name))
467 return vals
468 else:
469 return _config_vars
470
471def get_config_var(name):
472 """Return the value of a single variable using the dictionary
473 returned by 'get_config_vars()'. Equivalent to
474 get_config_vars().get(name)
475 """
476 return get_config_vars().get(name)