- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathsysconfig.py
550 lines (472 loc) · 20 KB
/
sysconfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
"""Provide access to Python's configuration information. The specific
configuration variables available depend heavily on the platform and
configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys(). Additional convenience functions are also
available.
Written by: Fred L. Drake, Jr.
Email: <fdrake@acm.org>
"""
import_imp
importos
importre
importsys
from .errorsimportDistutilsPlatformError
# These are needed in a couple of spots, so just compute them once.
PREFIX=os.path.normpath(sys.prefix)
EXEC_PREFIX=os.path.normpath(sys.exec_prefix)
BASE_PREFIX=os.path.normpath(sys.base_prefix)
BASE_EXEC_PREFIX=os.path.normpath(sys.base_exec_prefix)
# Path to the base directory of the project. On Windows the binary may
# live in project/PCbuild/win32 or project/PCbuild/amd64.
# set for cross builds
if"_PYTHON_PROJECT_BASE"inos.environ:
project_base=os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
else:
ifsys.executable:
project_base=os.path.dirname(os.path.abspath(sys.executable))
else:
# sys.executable can be empty if argv[0] has been changed and Python is
# unable to retrieve the real program name
project_base=os.getcwd()
# python_build: (Boolean) if true, we're either building Python or
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def_is_python_source_dir(d):
forfnin ("Setup.dist", "Setup.local"):
ifos.path.isfile(os.path.join(d, "Modules", fn)):
returnTrue
returnFalse
_sys_home=getattr(sys, '_home', None)
ifos.name=='nt':
def_fix_pcbuild(d):
ifdandos.path.normcase(d).startswith(
os.path.normcase(os.path.join(PREFIX, "PCbuild"))):
returnPREFIX
returnd
project_base=_fix_pcbuild(project_base)
_sys_home=_fix_pcbuild(_sys_home)
def_python_build():
if_sys_home:
return_is_python_source_dir(_sys_home)
return_is_python_source_dir(project_base)
python_build=_python_build()
# Calculate the build qualifier flags if they are defined. Adding the flags
# to the include and lib directories only makes sense for an installation, not
# an in-source build.
build_flags=''
try:
ifnotpython_build:
build_flags=sys.abiflags
exceptAttributeError:
# It's not a configure-based build, so the sys module doesn't have
# this attribute, which is fine.
pass
defget_python_version():
"""Return a string containing the major and minor Python version,
leaving off the patchlevel. Sample return values could be '1.5'
or '2.2'.
"""
return'%d.%d'%sys.version_info[:2]
defget_python_inc(plat_specific=0, prefix=None):
"""Return the directory containing installed Python header files.
If 'plat_specific' is false (the default), this is the path to the
non-platform-specific header files, i.e. Python.h and so on;
otherwise, this is the path to platform-specific header files
(namely pyconfig.h).
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
ifprefixisNone:
prefix=plat_specificandBASE_EXEC_PREFIXorBASE_PREFIX
ifos.name=="posix":
ifpython_build:
# Assume the executable is in the build directory. The
# pyconfig.h file should be in the same directory. Since
# the build directory may not be the source directory, we
# must use "srcdir" from the makefile to find the "Include"
# directory.
ifplat_specific:
return_sys_homeorproject_base
else:
incdir=os.path.join(get_config_var('srcdir'), 'Include')
returnos.path.normpath(incdir)
python_dir='python'+get_python_version() +build_flags
returnos.path.join(prefix, "include", python_dir)
elifos.name=="nt":
ifpython_build:
# Include both the include and PC dir to ensure we can find
# pyconfig.h
return (os.path.join(prefix, "include") +os.path.pathsep+
os.path.join(prefix, "PC"))
returnos.path.join(prefix, "include")
else:
raiseDistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'"%os.name)
defget_python_lib(plat_specific=0, standard_lib=0, prefix=None):
"""Return the directory containing the Python library (standard or
site additions).
If 'plat_specific' is true, return the directory containing
platform-specific modules, i.e. any module from a non-pure-Python
module distribution; otherwise, return the platform-shared library
directory. If 'standard_lib' is true, return the directory
containing standard Python library modules; otherwise, return the
directory for site-specific modules.
If 'prefix' is supplied, use it instead of sys.base_prefix or
sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
"""
ifprefixisNone:
ifstandard_lib:
prefix=plat_specificandBASE_EXEC_PREFIXorBASE_PREFIX
else:
prefix=plat_specificandEXEC_PREFIXorPREFIX
ifos.name=="posix":
libpython=os.path.join(prefix,
"lib", "python"+get_python_version())
ifstandard_lib:
returnlibpython
else:
returnos.path.join(libpython, "site-packages")
elifos.name=="nt":
ifstandard_lib:
returnos.path.join(prefix, "Lib")
else:
returnos.path.join(prefix, "Lib", "site-packages")
else:
raiseDistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'"%os.name)
defcustomize_compiler(compiler):
"""Do any platform-specific customization of a CCompiler instance.
Mainly needed on Unix, so we can plug in the information that
varies across Unices and is stored in Python's Makefile.
"""
ifcompiler.compiler_type=="unix":
ifsys.platform=="darwin":
# Perform first-time customization of compiler-related
# config vars on OS X now that we know we need a compiler.
# This is primarily to support Pythons from binary
# installers. The kind and paths to build tools on
# the user system may vary significantly from the system
# that Python itself was built on. Also the user OS
# version and build tools may not support the same set
# of CPU architectures for universal builds.
global_config_vars
# Use get_config_var() to ensure _config_vars is initialized.
ifnotget_config_var('CUSTOMIZED_OSX_COMPILER'):
import_osx_support
_osx_support.customize_compiler(_config_vars)
_config_vars['CUSTOMIZED_OSX_COMPILER'] ='True'
(cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
get_config_vars('CC', 'CXX', 'CFLAGS',
'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
if'CC'inos.environ:
newcc=os.environ['CC']
if (sys.platform=='darwin'
and'LDSHARED'notinos.environ
andldshared.startswith(cc)):
# On OS X, if CC is overridden, use that as the default
# command for LDSHARED as well
ldshared=newcc+ldshared[len(cc):]
cc=newcc
if'CXX'inos.environ:
cxx=os.environ['CXX']
if'LDSHARED'inos.environ:
ldshared=os.environ['LDSHARED']
if'CPP'inos.environ:
cpp=os.environ['CPP']
else:
cpp=cc+" -E"# not always
if'LDFLAGS'inos.environ:
ldshared=ldshared+' '+os.environ['LDFLAGS']
if'CFLAGS'inos.environ:
cflags=cflags+' '+os.environ['CFLAGS']
ldshared=ldshared+' '+os.environ['CFLAGS']
if'CPPFLAGS'inos.environ:
cpp=cpp+' '+os.environ['CPPFLAGS']
cflags=cflags+' '+os.environ['CPPFLAGS']
ldshared=ldshared+' '+os.environ['CPPFLAGS']
if'AR'inos.environ:
ar=os.environ['AR']
if'ARFLAGS'inos.environ:
archiver=ar+' '+os.environ['ARFLAGS']
else:
archiver=ar+' '+ar_flags
cc_cmd=cc+' '+cflags
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd+' '+ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc,
archiver=archiver)
compiler.shared_lib_extension=shlib_suffix
defget_config_h_filename():
"""Return full pathname of installed pyconfig.h file."""
ifpython_build:
ifos.name=="nt":
inc_dir=os.path.join(_sys_homeorproject_base, "PC")
else:
inc_dir=_sys_homeorproject_base
else:
inc_dir=get_python_inc(plat_specific=1)
returnos.path.join(inc_dir, 'pyconfig.h')
defget_makefile_filename():
"""Return full pathname of installed Makefile from the Python build."""
ifpython_build:
returnos.path.join(_sys_homeorproject_base, "Makefile")
lib_dir=get_python_lib(plat_specific=0, standard_lib=1)
config_file='config-{}{}'.format(get_python_version(), build_flags)
ifhasattr(sys.implementation, '_multiarch'):
config_file+='-%s'%sys.implementation._multiarch
returnos.path.join(lib_dir, config_file, 'Makefile')
defparse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
ifgisNone:
g= {}
define_rx=re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
undef_rx=re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
#
whileTrue:
line=fp.readline()
ifnotline:
break
m=define_rx.match(line)
ifm:
n, v=m.group(1, 2)
try: v=int(v)
exceptValueError: pass
g[n] =v
else:
m=undef_rx.match(line)
ifm:
g[m.group(1)] =0
returng
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx=re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx=re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx=re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
defparse_makefile(fn, g=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
fromdistutils.text_fileimportTextFile
fp=TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
ifgisNone:
g= {}
done= {}
notdone= {}
whileTrue:
line=fp.readline()
iflineisNone: # eof
break
m=_variable_rx.match(line)
ifm:
n, v=m.group(1, 2)
v=v.strip()
# `$$' is a literal `$' in make
tmpv=v.replace('$$', '')
if"$"intmpv:
notdone[n] =v
else:
try:
v=int(v)
exceptValueError:
# insert literal `$'
done[n] =v.replace('$$', '$')
else:
done[n] =v
# Variables with a 'PY_' prefix in the makefile. These need to
# be made available without that prefix through sysconfig.
# Special care is needed to ensure that variable expansion works, even
# if the expansion uses the name without a prefix.
renamed_variables= ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
# do variable interpolation here
whilenotdone:
fornameinlist(notdone):
value=notdone[name]
m=_findvar1_rx.search(value) or_findvar2_rx.search(value)
ifm:
n=m.group(1)
found=True
ifnindone:
item=str(done[n])
elifninnotdone:
# get it on a subsequent round
found=False
elifninos.environ:
# do it like make: fall back to environment
item=os.environ[n]
elifninrenamed_variables:
ifname.startswith('PY_') andname[3:] inrenamed_variables:
item=""
elif'PY_'+ninnotdone:
found=False
else:
item=str(done['PY_'+n])
else:
done[n] =item=""
iffound:
after=value[m.end():]
value=value[:m.start()] +item+after
if"$"inafter:
notdone[name] =value
else:
try: value=int(value)
exceptValueError:
done[name] =value.strip()
else:
done[name] =value
delnotdone[name]
ifname.startswith('PY_') \
andname[3:] inrenamed_variables:
name=name[3:]
ifnamenotindone:
done[name] =value
else:
# bogus variable reference; just drop it since we can't deal
delnotdone[name]
fp.close()
# strip spurious spaces
fork, vindone.items():
ifisinstance(v, str):
done[k] =v.strip()
# save the results in the global dictionary
g.update(done)
returng
defexpand_makefile_vars(s, vars):
"""Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
'string' according to 'vars' (a dictionary mapping variable names to
values). Variables not present in 'vars' are silently expanded to the
empty string. The variable values in 'vars' should not contain further
variable expansions; if 'vars' is the output of 'parse_makefile()',
you're fine. Returns a variable-expanded version of 's'.
"""
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
whileTrue:
m=_findvar1_rx.search(s) or_findvar2_rx.search(s)
ifm:
(beg, end) =m.span()
s=s[0:beg] +vars.get(m.group(1)) +s[end:]
else:
break
returns
_config_vars=None
def_init_posix():
"""Initialize the module as appropriate for POSIX systems."""
# _sysconfigdata is generated at build time, see the sysconfig module
name=os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
'_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
abi=sys.abiflags,
platform=sys.platform,
multiarch=getattr(sys.implementation, '_multiarch', ''),
))
_temp=__import__(name, globals(), locals(), ['build_time_vars'], 0)
build_time_vars=_temp.build_time_vars
global_config_vars
_config_vars= {}
_config_vars.update(build_time_vars)
def_init_nt():
"""Initialize the module as appropriate for NT"""
g= {}
# set basic install directories
g['LIBDEST'] =get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] =get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] =get_python_inc(plat_specific=0)
g['EXT_SUFFIX'] =_imp.extension_suffixes()[0]
g['EXE'] =".exe"
g['VERSION'] =get_python_version().replace(".", "")
g['BINDIR'] =os.path.dirname(os.path.abspath(sys.executable))
global_config_vars
_config_vars=g
defget_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform. Generally this includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global_config_vars
if_config_varsisNone:
func=globals().get("_init_"+os.name)
iffunc:
func()
else:
_config_vars= {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# Distutils.
_config_vars['prefix'] =PREFIX
_config_vars['exec_prefix'] =EXEC_PREFIX
# For backward compatibility, see issue19555
SO=_config_vars.get('EXT_SUFFIX')
ifSOisnotNone:
_config_vars['SO'] =SO
# Always convert srcdir to an absolute path
srcdir=_config_vars.get('srcdir', project_base)
ifos.name=='posix':
ifpython_build:
# If srcdir is a relative path (typically '.' or '..')
# then it should be interpreted relative to the directory
# containing Makefile.
base=os.path.dirname(get_makefile_filename())
srcdir=os.path.join(base, srcdir)
else:
# srcdir is not meaningful since the installation is
# spread about the filesystem. We choose the
# directory containing the Makefile since we know it
# exists.
srcdir=os.path.dirname(get_makefile_filename())
_config_vars['srcdir'] =os.path.abspath(os.path.normpath(srcdir))
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
ifpython_buildandos.name=="posix":
base=project_base
if (notos.path.isabs(_config_vars['srcdir']) and
base!=os.getcwd()):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir=os.path.join(base, _config_vars['srcdir'])
_config_vars['srcdir'] =os.path.normpath(srcdir)
# OS X platforms require special customization to handle
# multi-architecture, multi-os-version installers
ifsys.platform=='darwin':
import_osx_support
_osx_support.customize_config_vars(_config_vars)
ifargs:
vals= []
fornameinargs:
vals.append(_config_vars.get(name))
returnvals
else:
return_config_vars
defget_config_var(name):
"""Return the value of a single variable using the dictionary
returned by 'get_config_vars()'. Equivalent to
get_config_vars().get(name)
"""
ifname=='SO':
importwarnings
warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
returnget_config_vars().get(name)