home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / SYSCONFIG.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  13.6 KB  |  392 lines

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