home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / SYSCONFIG.PY < prev    next >
Encoding:
Python Source  |  2001-12-06  |  14.8 KB  |  432 lines

  1. """Provide access to Python's configuration information.  The specific
  2. configuration variables available depend heavily on the platform and
  3. configuration.  The values may be retrieved using
  4. get_config_var(name), and the list of variables is available via
  5. get_config_vars().keys().  Additional convenience functions are also
  6. available.
  7.  
  8. Written by:   Fred L. Drake, Jr.
  9. Email:        <fdrake@acm.org>
  10. Initial date: 17-Dec-1998
  11. """
  12.  
  13. __revision__ = "$Id: sysconfig.py,v 1.44 2001/12/06 20:51:35 fdrake Exp $"
  14.  
  15. import os
  16. import re
  17. import string
  18. import sys
  19.  
  20. from errors import DistutilsPlatformError
  21.  
  22. # These are needed in a couple of spots, so just compute them once.
  23. PREFIX = os.path.normpath(sys.prefix)
  24. EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
  25.  
  26. # Boolean; if it's true, we're still building Python, so
  27. # we use different (hard-wired) directories.
  28.  
  29. python_build = 0
  30.  
  31. def set_python_build():
  32.     """Set the python_build flag to true.
  33.  
  34.     This means that we're building Python itself.  Only called from
  35.     the setup.py script shipped with Python.
  36.     """
  37.     global python_build
  38.     python_build = 1
  39.  
  40.  
  41. def get_python_inc(plat_specific=0, prefix=None):
  42.     """Return the directory containing installed Python header files.
  43.  
  44.     If 'plat_specific' is false (the default), this is the path to the
  45.     non-platform-specific header files, i.e. Python.h and so on;
  46.     otherwise, this is the path to platform-specific header files
  47.     (namely pyconfig.h).
  48.  
  49.     If 'prefix' is supplied, use it instead of sys.prefix or
  50.     sys.exec_prefix -- i.e., ignore 'plat_specific'.
  51.     """
  52.     if prefix is None:
  53.         prefix = plat_specific and EXEC_PREFIX or PREFIX
  54.     if os.name == "posix":
  55.         if python_build:
  56.             return "Include/"
  57.         return os.path.join(prefix, "include", "python" + sys.version[:3])
  58.     elif os.name == "nt":
  59.         return os.path.join(prefix, "include")
  60.     elif os.name == "mac":
  61.         return os.path.join(prefix, "Include")
  62.     else:
  63.         raise DistutilsPlatformError(
  64.             "I don't know where Python installs its C header files "
  65.             "on platform '%s'" % os.name)
  66.  
  67.  
  68. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  69.     """Return the directory containing the Python library (standard or
  70.     site additions).
  71.  
  72.     If 'plat_specific' is true, return the directory containing
  73.     platform-specific modules, i.e. any module from a non-pure-Python
  74.     module distribution; otherwise, return the platform-shared library
  75.     directory.  If 'standard_lib' is true, return the directory
  76.     containing standard Python library modules; otherwise, return the
  77.     directory for site-specific modules.
  78.  
  79.     If 'prefix' is supplied, use it instead of sys.prefix or
  80.     sys.exec_prefix -- i.e., ignore 'plat_specific'.
  81.     """
  82.     if prefix is None:
  83.         prefix = plat_specific and EXEC_PREFIX or PREFIX
  84.  
  85.     if os.name == "posix":
  86.         libpython = os.path.join(prefix,
  87.                                  "lib", "python" + sys.version[:3])
  88.         if standard_lib:
  89.             return libpython
  90.         else:
  91.             return os.path.join(libpython, "site-packages")
  92.  
  93.     elif os.name == "nt":
  94.         if standard_lib:
  95.             return os.path.join(prefix, "Lib")
  96.         else:
  97.             if sys.version < "2.2":
  98.                 return prefix
  99.             else:
  100.                 return os.path.join(PREFIX, "Lib", "site-packages")
  101.  
  102.     elif os.name == "mac":
  103.         if plat_specific:
  104.             if standard_lib:
  105.                 return os.path.join(prefix, "Lib", "lib-dynload")
  106.             else:
  107.                 return os.path.join(prefix, "Lib", "site-packages")
  108.         else:
  109.             if standard_lib:
  110.                 return os.path.join(prefix, "Lib")
  111.             else:
  112.                 return os.path.join(prefix, "Lib", "site-packages")
  113.     else:
  114.         raise DistutilsPlatformError(
  115.             "I don't know where Python installs its library "
  116.             "on platform '%s'" % os.name)
  117.  
  118.  
  119. def customize_compiler(compiler):
  120.     """Do any platform-specific customization of a CCompiler instance.
  121.  
  122.     Mainly needed on Unix, so we can plug in the information that
  123.     varies across Unices and is stored in Python's Makefile.
  124.     """
  125.     if compiler.compiler_type == "unix":
  126.         (cc, opt, ccshared, ldshared, so_ext) = \
  127.             get_config_vars('CC', 'OPT', 'CCSHARED', 'LDSHARED', 'SO')
  128.  
  129.         cc_cmd = cc + ' ' + opt
  130.         compiler.set_executables(
  131.             preprocessor=cc + " -E",    # not always!
  132.             compiler=cc_cmd,
  133.             compiler_so=cc_cmd + ' ' + ccshared,
  134.             linker_so=ldshared,
  135.             linker_exe=cc)
  136.  
  137.         compiler.shared_lib_extension = so_ext
  138.  
  139.  
  140. def get_config_h_filename():
  141.     """Return full pathname of installed pyconfig.h file."""
  142.     if python_build:
  143.         inc_dir = os.curdir
  144.     else:
  145.         inc_dir = get_python_inc(plat_specific=1)
  146.     if sys.version < '2.2':
  147.         config_h = 'config.h'
  148.     else:
  149.         # The name of the config.h file changed in 2.2
  150.         config_h = 'pyconfig.h'
  151.     return os.path.join(inc_dir, config_h)
  152.  
  153.  
  154. def get_makefile_filename():
  155.     """Return full pathname of installed Makefile from the Python build."""
  156.     if python_build:
  157.         return './Makefile'
  158.     lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
  159.     return os.path.join(lib_dir, "config", "Makefile")
  160.  
  161.  
  162. def parse_config_h(fp, g=None):
  163.     """Parse a config.h-style file.
  164.  
  165.     A dictionary containing name/value pairs is returned.  If an
  166.     optional dictionary is passed in as the second argument, it is
  167.     used instead of a new dictionary.
  168.     """
  169.     if g is None:
  170.         g = {}
  171.     define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n")
  172.     undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
  173.     #
  174.     while 1:
  175.         line = fp.readline()
  176.         if not line:
  177.             break
  178.         m = define_rx.match(line)
  179.         if m:
  180.             n, v = m.group(1, 2)
  181.             try: v = string.atoi(v)
  182.             except ValueError: pass
  183.             g[n] = v
  184.         else:
  185.             m = undef_rx.match(line)
  186.             if m:
  187.                 g[m.group(1)] = 0
  188.     return g
  189.  
  190.  
  191. # Regexes needed for parsing Makefile (and similar syntaxes,
  192. # like old-style Setup files).
  193. _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  194. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  195. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  196.  
  197. def parse_makefile(fn, g=None):
  198.     """Parse a Makefile-style file.
  199.  
  200.     A dictionary containing name/value pairs is returned.  If an
  201.     optional dictionary is passed in as the second argument, it is
  202.     used instead of a new dictionary.
  203.     """
  204.     from distutils.text_file import TextFile
  205.     fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
  206.  
  207.     if g is None:
  208.         g = {}
  209.     done = {}
  210.     notdone = {}
  211.  
  212.     while 1:
  213.         line = fp.readline()
  214.         if line is None:                # eof
  215.             break
  216.         m = _variable_rx.match(line)
  217.         if m:
  218.             n, v = m.group(1, 2)
  219.             v = string.strip(v)
  220.             if "$" in v:
  221.                 notdone[n] = v
  222.             else:
  223.                 try: v = string.atoi(v)
  224.                 except ValueError: pass
  225.                 done[n] = v
  226.  
  227.     # do variable interpolation here
  228.     while notdone:
  229.         for name in notdone.keys():
  230.             value = notdone[name]
  231.             m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  232.             if m:
  233.                 n = m.group(1)
  234.                 if done.has_key(n):
  235.                     after = value[m.end():]
  236.                     value = value[:m.start()] + str(done[n]) + after
  237.                     if "$" in after:
  238.                         notdone[name] = value
  239.                     else:
  240.                         try: value = string.atoi(value)
  241.                         except ValueError:
  242.                             done[name] = string.strip(value)
  243.                         else:
  244.                             done[name] = value
  245.                         del notdone[name]
  246.                 elif notdone.has_key(n):
  247.                     # get it on a subsequent round
  248.                     pass
  249.                 else:
  250.                     done[n] = ""
  251.                     after = value[m.end():]
  252.                     value = value[:m.start()] + after
  253.                     if "$" in after:
  254.                         notdone[name] = value
  255.                     else:
  256.                         try: value = string.atoi(value)
  257.                         except ValueError:
  258.                             done[name] = string.strip(value)
  259.                         else:
  260.                             done[name] = value
  261.                         del notdone[name]
  262.             else:
  263.                 # bogus variable reference; just drop it since we can't deal
  264.                 del notdone[name]
  265.  
  266.     fp.close()
  267.  
  268.     # save the results in the global dictionary
  269.     g.update(done)
  270.     return g
  271.  
  272.  
  273. def expand_makefile_vars(s, vars):
  274.     """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  275.     'string' according to 'vars' (a dictionary mapping variable names to
  276.     values).  Variables not present in 'vars' are silently expanded to the
  277.     empty string.  The variable values in 'vars' should not contain further
  278.     variable expansions; if 'vars' is the output of 'parse_makefile()',
  279.     you're fine.  Returns a variable-expanded version of 's'.
  280.     """
  281.  
  282.     # This algorithm does multiple expansion, so if vars['foo'] contains
  283.     # "${bar}", it will expand ${foo} to ${bar}, and then expand
  284.     # ${bar}... and so forth.  This is fine as long as 'vars' comes from
  285.     # 'parse_makefile()', which takes care of such expansions eagerly,
  286.     # according to make's variable expansion semantics.
  287.  
  288.     while 1:
  289.         m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  290.         if m:
  291.             name = m.group(1)
  292.             (beg, end) = m.span()
  293.             s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  294.         else:
  295.             break
  296.     return s
  297.  
  298.  
  299. _config_vars = None
  300.  
  301. def _init_posix():
  302.     """Initialize the module as appropriate for POSIX systems."""
  303.     g = {}
  304.     # load the installed Makefile:
  305.     try:
  306.         filename = get_makefile_filename()
  307.         parse_makefile(filename, g)
  308.     except IOError, msg:
  309.         my_msg = "invalid Python installation: unable to open %s" % filename
  310.         if hasattr(msg, "strerror"):
  311.             my_msg = my_msg + " (%s)" % msg.strerror
  312.  
  313.         raise DistutilsPlatformError(my_msg)
  314.  
  315.  
  316.     # On AIX, there are wrong paths to the linker scripts in the Makefile
  317.     # -- these paths are relative to the Python source, but when installed
  318.     # the scripts are in another directory.
  319.     if python_build:
  320.         g['LDSHARED'] = g['BLDSHARED']
  321.  
  322.     elif sys.version < '2.1':
  323.         # The following two branches are for 1.5.2 compatibility.
  324.         if sys.platform == 'aix4':          # what about AIX 3.x ?
  325.             # Linker script is in the config directory, not in Modules as the
  326.             # Makefile says.
  327.             python_lib = get_python_lib(standard_lib=1)
  328.             ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
  329.             python_exp = os.path.join(python_lib, 'config', 'python.exp')
  330.  
  331.             g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
  332.  
  333.         elif sys.platform == 'beos':
  334.             # Linker script is in the config directory.  In the Makefile it is
  335.             # relative to the srcdir, which after installation no longer makes
  336.             # sense.
  337.             python_lib = get_python_lib(standard_lib=1)
  338.             linkerscript_name = os.path.basename(string.split(g['LDSHARED'])[0])
  339.             linkerscript = os.path.join(python_lib, 'config', linkerscript_name)
  340.  
  341.             # XXX this isn't the right place to do this: adding the Python
  342.             # library to the link, if needed, should be in the "build_ext"
  343.             # command.  (It's also needed for non-MS compilers on Windows, and
  344.             # it's taken care of for them by the 'build_ext.get_libraries()'
  345.             # method.)
  346.             g['LDSHARED'] = ("%s -L%s/lib -lpython%s" %
  347.                              (linkerscript, PREFIX, sys.version[0:3]))
  348.  
  349.     global _config_vars
  350.     _config_vars = g
  351.  
  352.  
  353. def _init_nt():
  354.     """Initialize the module as appropriate for NT"""
  355.     g = {}
  356.     # set basic install directories
  357.     g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  358.     g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  359.  
  360.     # XXX hmmm.. a normal install puts include files here
  361.     g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  362.  
  363.     g['SO'] = '.pyd'
  364.     g['EXE'] = ".exe"
  365.  
  366.     global _config_vars
  367.     _config_vars = g
  368.  
  369.  
  370. def _init_mac():
  371.     """Initialize the module as appropriate for Macintosh systems"""
  372.     g = {}
  373.     # set basic install directories
  374.     g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  375.     g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  376.  
  377.     # XXX hmmm.. a normal install puts include files here
  378.     g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  379.  
  380.     import MacOS
  381.     if not hasattr(MacOS, 'runtimemodel'):
  382.         g['SO'] = '.ppc.slb'
  383.     else:
  384.         g['SO'] = '.%s.slb' % MacOS.runtimemodel
  385.  
  386.     # XXX are these used anywhere?
  387.     g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")
  388.     g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")
  389.  
  390.     global _config_vars
  391.     _config_vars = g
  392.  
  393.  
  394. def get_config_vars(*args):
  395.     """With no arguments, return a dictionary of all configuration
  396.     variables relevant for the current platform.  Generally this includes
  397.     everything needed to build extensions and install both pure modules and
  398.     extensions.  On Unix, this means every variable defined in Python's
  399.     installed Makefile; on Windows and Mac OS it's a much smaller set.
  400.  
  401.     With arguments, return a list of values that result from looking up
  402.     each argument in the configuration variable dictionary.
  403.     """
  404.     global _config_vars
  405.     if _config_vars is None:
  406.         func = globals().get("_init_" + os.name)
  407.         if func:
  408.             func()
  409.         else:
  410.             _config_vars = {}
  411.  
  412.         # Normalized versions of prefix and exec_prefix are handy to have;
  413.         # in fact, these are the standard versions used most places in the
  414.         # Distutils.
  415.         _config_vars['prefix'] = PREFIX
  416.         _config_vars['exec_prefix'] = EXEC_PREFIX
  417.  
  418.     if args:
  419.         vals = []
  420.         for name in args:
  421.             vals.append(_config_vars.get(name))
  422.         return vals
  423.     else:
  424.         return _config_vars
  425.  
  426. def get_config_var(name):
  427.     """Return the value of a single variable using the dictionary
  428.     returned by 'get_config_vars()'.  Equivalent to
  429.     get_config_vars().get(name)
  430.     """
  431.     return get_config_vars().get(name)
  432.