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 / CORE.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  8.2 KB  |  232 lines

  1. """distutils.core
  2.  
  3. The only module that needs to be imported to use the Distutils; provides
  4. the 'setup' function (which is to be called from the setup script).  Also
  5. indirectly provides the Distribution and Command classes, although they are
  6. really defined in distutils.dist and distutils.cmd.
  7. """
  8.  
  9. # created 1999/03/01, Greg Ward
  10.  
  11. __revision__ = "$Id: core.py,v 1.46 2000/09/26 01:48:44 gward Exp $"
  12.  
  13. import sys, os
  14. from types import *
  15. from distutils.errors import *
  16. from distutils.util import grok_environment_error
  17.  
  18. # Mainly import these so setup scripts can "from distutils.core import" them.
  19. from distutils.dist import Distribution
  20. from distutils.cmd import Command
  21. from distutils.extension import Extension
  22.  
  23.  
  24. # This is a barebones help message generated displayed when the user
  25. # runs the setup script with no arguments at all.  More useful help
  26. # is generated with various --help options: global help, list commands,
  27. # and per-command help.
  28. USAGE = """\
  29. usage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
  30.    or: %(script)s --help [cmd1 cmd2 ...]
  31.    or: %(script)s --help-commands
  32.    or: %(script)s cmd --help
  33. """
  34.  
  35.  
  36. # If DISTUTILS_DEBUG is anything other than the empty string, we run in
  37. # debug mode.
  38. DEBUG = os.environ.get('DISTUTILS_DEBUG')
  39.  
  40. def gen_usage (script_name):
  41.     script = os.path.basename(script_name)
  42.     return USAGE % vars()
  43.  
  44.  
  45. # Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.
  46. _setup_stop_after = None
  47. _setup_distribution = None
  48.  
  49.  
  50. def setup (**attrs):
  51.     """The gateway to the Distutils: do everything your setup script needs
  52.     to do, in a highly flexible and user-driven way.  Briefly: create a
  53.     Distribution instance; find and parse config files; parse the command
  54.     line; run each Distutils command found there, customized by the options
  55.     supplied to 'setup()' (as keyword arguments), in config files, and on
  56.     the command line.
  57.  
  58.     The Distribution instance might be an instance of a class supplied via
  59.     the 'distclass' keyword argument to 'setup'; if no such class is
  60.     supplied, then the Distribution class (in dist.py) is instantiated.
  61.     All other arguments to 'setup' (except for 'cmdclass') are used to set
  62.     attributes of the Distribution instance.
  63.  
  64.     The 'cmdclass' argument, if supplied, is a dictionary mapping command
  65.     names to command classes.  Each command encountered on the command line
  66.     will be turned into a command class, which is in turn instantiated; any
  67.     class found in 'cmdclass' is used in place of the default, which is
  68.     (for command 'foo_bar') class 'foo_bar' in module
  69.     'distutils.command.foo_bar'.  The command class must provide a
  70.     'user_options' attribute which is a list of option specifiers for
  71.     'distutils.fancy_getopt'.  Any command-line options between the current
  72.     and the next command are used to set attributes of the current command
  73.     object.
  74.  
  75.     When the entire command-line has been successfully parsed, calls the
  76.     'run()' method on each command object in turn.  This method will be
  77.     driven entirely by the Distribution object (which each command object
  78.     has a reference to, thanks to its constructor), and the
  79.     command-specific options that became attributes of each command
  80.     object.
  81.     """
  82.  
  83.     global _setup_stop_after, _setup_distribution
  84.  
  85.     # Determine the distribution class -- either caller-supplied or
  86.     # our Distribution (see below).
  87.     klass = attrs.get('distclass')
  88.     if klass:
  89.         del attrs['distclass']
  90.     else:
  91.         klass = Distribution
  92.  
  93.     if not attrs.has_key('script_name'):
  94.         attrs['script_name'] = sys.argv[0]
  95.     if not attrs.has_key('script_args'):
  96.         attrs['script_args'] = sys.argv[1:]
  97.  
  98.     # Create the Distribution instance, using the remaining arguments
  99.     # (ie. everything except distclass) to initialize it
  100.     try:
  101.         _setup_distribution = dist = klass(attrs)
  102.     except DistutilsSetupError, msg:
  103.         raise SystemExit, "error in setup script: %s" % msg
  104.  
  105.     if _setup_stop_after == "init":
  106.         return dist
  107.  
  108.     # Find and parse the config file(s): they will override options from
  109.     # the setup script, but be overridden by the command line.
  110.     dist.parse_config_files()
  111.     
  112.     if DEBUG:
  113.         print "options (after parsing config files):"
  114.         dist.dump_option_dicts()
  115.  
  116.     if _setup_stop_after == "config":
  117.         return dist
  118.  
  119.     # Parse the command line; any command-line errors are the end user's
  120.     # fault, so turn them into SystemExit to suppress tracebacks.
  121.     try:
  122.         ok = dist.parse_command_line()
  123.     except DistutilsArgError, msg:
  124.         script = os.path.basename(dist.script_name)
  125.         raise SystemExit, \
  126.               gen_usage(dist.script_name) + "\nerror: %s" % msg
  127.  
  128.     if DEBUG:
  129.         print "options (after parsing command line):"
  130.         dist.dump_option_dicts()
  131.  
  132.     if _setup_stop_after == "commandline":
  133.         return dist
  134.  
  135.     # And finally, run all the commands found on the command line.
  136.     if ok:
  137.         try:
  138.             dist.run_commands()
  139.         except KeyboardInterrupt:
  140.             raise SystemExit, "interrupted"
  141.         except (IOError, os.error), exc:
  142.             error = grok_environment_error(exc)
  143.  
  144.             if DEBUG:
  145.                 sys.stderr.write(error + "\n")
  146.                 raise
  147.             else:
  148.                 raise SystemExit, error
  149.             
  150.         except (DistutilsExecError,
  151.                 DistutilsFileError,
  152.                 DistutilsOptionError,
  153.                 CCompilerError), msg:
  154.             if DEBUG:
  155.                 raise
  156.             else:
  157.                 raise SystemExit, "error: " + str(msg)
  158.  
  159.     return dist
  160.  
  161. # setup ()
  162.  
  163.  
  164. def run_setup (script_name, script_args=None, stop_after="run"):
  165.     """Run a setup script in a somewhat controlled environment, and
  166.     return the Distribution instance that drives things.  This is useful
  167.     if you need to find out the distribution meta-data (passed as
  168.     keyword args from 'script' to 'setup()', or the contents of the
  169.     config files or command-line.
  170.  
  171.     'script_name' is a file that will be run with 'execfile()';
  172.     'sys.argv[0]' will be replaced with 'script' for the duration of the
  173.     call.  'script_args' is a list of strings; if supplied,
  174.     'sys.argv[1:]' will be replaced by 'script_args' for the duration of
  175.     the call.
  176.  
  177.     'stop_after' tells 'setup()' when to stop processing; possible
  178.     values:
  179.       init
  180.         stop after the Distribution instance has been created and
  181.         populated with the keyword arguments to 'setup()'
  182.       config
  183.         stop after config files have been parsed (and their data
  184.         stored in the Distribution instance)
  185.       commandline
  186.         stop after the command-line ('sys.argv[1:]' or 'script_args')
  187.         have been parsed (and the data stored in the Distribution)
  188.       run [default]
  189.         stop after all commands have been run (the same as if 'setup()'
  190.         had been called in the usual way
  191.  
  192.     Returns the Distribution instance, which provides all information
  193.     used to drive the Distutils.
  194.     """
  195.     if stop_after not in ('init', 'config', 'commandline', 'run'):
  196.         raise ValueError, "invalid value for 'stop_after': %s" % `stop_after`
  197.  
  198.     global _setup_stop_after, _setup_distribution
  199.     _setup_stop_after = stop_after
  200.  
  201.     save_argv = sys.argv
  202.     g = {}
  203.     l = {}
  204.     try:
  205.         try:
  206.             sys.argv[0] = script_name
  207.             if script_args is not None:
  208.                 sys.argv[1:] = script_args
  209.             execfile(script_name, g, l)
  210.         finally:
  211.             sys.argv = save_argv
  212.             _setup_stop_after = None
  213.     except SystemExit:
  214.         # Hmm, should we do something if exiting with a non-zero code
  215.         # (ie. error)?
  216.         pass
  217.     except:
  218.         raise
  219.  
  220.     if _setup_distribution is None:
  221.         raise RuntimeError, \
  222.               ("'distutils.core.setup()' was never called -- "
  223.                "perhaps '%s' is not a Distutils setup script?") % \
  224.               script_name
  225.  
  226.     # I wonder if the setup script's namespace -- g and l -- would be of
  227.     # any interest to callers?
  228.     #print "_setup_distribution:", _setup_distribution
  229.     return _setup_distribution
  230.  
  231. # run_setup ()
  232.