desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Compile \'src\' to product \'obj\'.'
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
pass
'Link a bunch of stuff together to create a static library file. The "bunch of stuff" consists of the list of object files supplied as \'objects\', the extra object files supplied to \'add_link_object()\' and/or \'set_link_objects()\', the libraries supplied to \'add_library()\' and/or \'set_libraries()\', and the libraries supplied as \'libraries\' (if any). \'output_libname\' should be a library name, not a filename; the filename will be inferred from the library name. \'output_dir\' is the directory where the library file will be put. \'debug\' is a boolean; if true, debugging information will be included in the library (note that on most platforms, it is the compile step where this matters: the \'debug\' flag is included here just for consistency). \'target_lang\' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LibError on failure.'
def create_static_lib(self, objects, output_libname, output_dir=None, debug=0, target_lang=None):
pass
'Link a bunch of stuff together to create an executable or shared library file. The "bunch of stuff" consists of the list of object files supplied as \'objects\'. \'output_filename\' should be a filename. If \'output_dir\' is supplied, \'output_filename\' is relative to it (i.e. \'output_filename\' can provide directory components if needed). \'libraries\' is a list of libraries to link against. These are library names, not filenames, since they\'re translated into filenames in a platform-specific way (eg. "foo" becomes "libfoo.a" on Unix and "foo.lib" on DOS/Windows). However, they can include a directory component, which means the linker will look in that specific directory rather than searching all the normal locations. \'library_dirs\', if supplied, should be a list of directories to search for libraries that were specified as bare library names (ie. no directory component). These are on top of the system default and those supplied to \'add_library_dir()\' and/or \'set_library_dirs()\'. \'runtime_library_dirs\' is a list of directories that will be embedded into the shared library and used to search for other shared libraries that *it* depends on at run-time. (This may only be relevant on Unix.) \'export_symbols\' is a list of symbols that the shared library will export. (This appears to be relevant only on Windows.) \'debug\' is as for \'compile()\' and \'create_static_lib()\', with the slight distinction that it actually matters on most platforms (as opposed to \'create_static_lib()\', which includes a \'debug\' flag mostly for form\'s sake). \'extra_preargs\' and \'extra_postargs\' are as for \'compile()\' (except of course that they supply command-line arguments for the particular linker being used). \'target_lang\' is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages. Raises LinkError on failure.'
def link(self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None):
raise NotImplementedError
'Return the compiler option to add \'dir\' to the list of directories searched for libraries.'
def library_dir_option(self, dir):
raise NotImplementedError
'Return the compiler option to add \'dir\' to the list of directories searched for runtime libraries.'
def runtime_library_dir_option(self, dir):
raise NotImplementedError
'Return the compiler option to add \'dir\' to the list of libraries linked into the shared library or executable.'
def library_option(self, lib):
raise NotImplementedError
'Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment.'
def has_function(self, funcname, includes=None, include_dirs=None, libraries=None, library_dirs=None):
import tempfile if (includes is None): includes = [] if (include_dirs is None): include_dirs = [] if (libraries is None): libraries = [] if (library_dirs is None): library_dirs = [] (fd, fname) = tempfile.mkstemp('.c', funcname, text=True) f = os.fdopen(fd, 'w') try: for incl in includes: f.write(('#include "%s"\n' % incl)) f.write(('main (int argc, char **argv) {\n %s();\n}\n' % funcname)) finally: f.close() try: objects = self.compile([fname], include_dirs=include_dirs) except CompileError: return False try: self.link_executable(objects, 'a.out', libraries=libraries, library_dirs=library_dirs) except (LinkError, TypeError): return False return True
'Search the specified list of directories for a static or shared library file \'lib\' and return the full path to that file. If \'debug\' true, look for a debugging version (if that makes sense on the current platform). Return None if \'lib\' wasn\'t found in any of the specified directories.'
def find_library_file(self, dirs, lib, debug=0):
raise NotImplementedError
'Returns rc file path.'
def _get_rc_file(self):
return os.path.join(os.path.expanduser('~'), '.pypirc')
'Creates a default .pypirc file.'
def _store_pypirc(self, username, password):
rc = self._get_rc_file() f = open(rc, 'w') try: f.write((DEFAULT_PYPIRC % (username, password))) finally: f.close() try: os.chmod(rc, 384) except OSError: pass
'Reads the .pypirc file.'
def _read_pypirc(self):
rc = self._get_rc_file() if os.path.exists(rc): self.announce(('Using PyPI login from %s' % rc)) repository = (self.repository or self.DEFAULT_REPOSITORY) config = ConfigParser() config.read(rc) sections = config.sections() if ('distutils' in sections): index_servers = config.get('distutils', 'index-servers') _servers = [server.strip() for server in index_servers.split('\n') if (server.strip() != '')] if (_servers == []): if ('pypi' in sections): _servers = ['pypi'] else: return {} for server in _servers: current = {'server': server} current['username'] = config.get(server, 'username') for (key, default) in (('repository', self.DEFAULT_REPOSITORY), ('realm', self.DEFAULT_REALM), ('password', None)): if config.has_option(server, key): current[key] = config.get(server, key) else: current[key] = default if ((current['server'] == repository) or (current['repository'] == repository)): return current elif ('server-login' in sections): server = 'server-login' if config.has_option(server, 'repository'): repository = config.get(server, 'repository') else: repository = self.DEFAULT_REPOSITORY return {'username': config.get(server, 'username'), 'password': config.get(server, 'password'), 'repository': repository, 'server': server, 'realm': self.DEFAULT_REALM} return {}
'Initialize options.'
def initialize_options(self):
self.repository = None self.realm = None self.show_response = 0
'Finalizes options.'
def finalize_options(self):
if (self.repository is None): self.repository = self.DEFAULT_REPOSITORY if (self.realm is None): self.realm = self.DEFAULT_REALM
'Patches the environment.'
def setUp(self):
super(PyPIRCCommandTestCase, self).setUp() self.tmp_dir = self.mkdtemp() os.environ['HOME'] = self.tmp_dir self.rc = os.path.join(self.tmp_dir, '.pypirc') self.dist = Distribution() class command(PyPIRCCommand, ): def __init__(self, dist): PyPIRCCommand.__init__(self, dist) def initialize_options(self): pass finalize_options = initialize_options self._cmd = command self.old_threshold = set_threshold(WARN)
'Removes the patch.'
def tearDown(self):
set_threshold(self.old_threshold) super(PyPIRCCommandTestCase, self).tearDown()
'Build extensions in build directory, then copy if --inplace'
def run(self):
(old_inplace, self.inplace) = (self.inplace, 0) _build_ext.run(self) self.inplace = old_inplace if old_inplace: self.copy_extensions_to_source()
'Return true if \'ext\' links to a dynamic lib in the same package'
def links_to_dynamic(self, ext):
libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join((ext._full_name.split('.')[:(-1)] + [''])) for libname in ext.libraries: if ((pkg + libname) in libnames): return True return False
'Create a temporary directory that will be cleaned up. Returns the path of the directory.'
def mkdtemp(self):
d = tempfile.mkdtemp() self.tempdirs.append(d) return d
'Writes a file in the given path. path can be a string or a sequence.'
def write_file(self, path, content='xxx'):
if isinstance(path, (list, tuple)): path = os.path.join(*path) f = open(path, 'w') try: f.write(content) finally: f.close()
'Will generate a test environment. This function creates: - a Distribution instance using keywords - a temporary directory with a package structure It returns the package directory and the distribution instance.'
def create_dist(self, pkg_name='foo', **kw):
tmp_dir = self.mkdtemp() pkg_dir = os.path.join(tmp_dir, pkg_name) os.mkdir(pkg_dir) dist = Distribution(attrs=kw) return (pkg_dir, dist)
'Returns a cmd'
def get_cmd(self, metadata=None):
if (metadata is None): metadata = {'name': 'fake', 'version': '1.0', 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'} dist = Distribution(metadata) dist.script_name = 'setup.py' dist.packages = ['somecode'] dist.include_package_data = True cmd = sdist(dist) cmd.dist_dir = 'dist' def _warn(*args): pass cmd.warn = _warn return (dist, cmd)
'Return true if the option table for this parser has an option with long name \'long_option\'.'
def has_option(self, long_option):
return (long_option in self.option_index)
'Translate long option name \'long_option\' to the form it has as an attribute of some object: ie., translate hyphens to underscores.'
def get_attr_name(self, long_option):
return string.translate(long_option, longopt_xlate)
'Set the aliases for this option parser.'
def set_aliases(self, alias):
self._check_alias_dict(alias, 'alias') self.alias = alias
'Set the negative aliases for this option parser. \'negative_alias\' should be a dictionary mapping option names to option names, both the key and value must already be defined in the option table.'
def set_negative_aliases(self, negative_alias):
self._check_alias_dict(negative_alias, 'negative alias') self.negative_alias = negative_alias
'Populate the various data structures that keep tabs on the option table. Called by \'getopt()\' before it can do anything worthwhile.'
def _grok_option_table(self):
self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {} for option in self.option_table: if (len(option) == 3): (long, short, help) = option repeat = 0 elif (len(option) == 4): (long, short, help, repeat) = option else: raise ValueError, ('invalid option tuple: %r' % (option,)) if ((not isinstance(long, str)) or (len(long) < 2)): raise DistutilsGetoptError, ("invalid long option '%s': must be a string of length >= 2" % long) if (not ((short is None) or (isinstance(short, str) and (len(short) == 1)))): raise DistutilsGetoptError, ("invalid short option '%s': must a single character or None" % short) self.repeat[long] = repeat self.long_opts.append(long) if (long[(-1)] == '='): if short: short = (short + ':') long = long[0:(-1)] self.takes_arg[long] = 1 else: alias_to = self.negative_alias.get(long) if (alias_to is not None): if self.takes_arg[alias_to]: raise DistutilsGetoptError, ("invalid negative alias '%s': aliased option '%s' takes a value" % (long, alias_to)) self.long_opts[(-1)] = long self.takes_arg[long] = 0 else: self.takes_arg[long] = 0 alias_to = self.alias.get(long) if (alias_to is not None): if (self.takes_arg[long] != self.takes_arg[alias_to]): raise DistutilsGetoptError, ("invalid alias '%s': inconsistent with aliased option '%s' (one of them takes a value, the other doesn't" % (long, alias_to)) if (not longopt_re.match(long)): raise DistutilsGetoptError, (("invalid long option name '%s' " + '(must be letters, numbers, hyphens only') % long) self.attr_name[long] = self.get_attr_name(long) if short: self.short_opts.append(short) self.short2long[short[0]] = long
'Parse command-line options in args. Store as attributes on object. If \'args\' is None or not supplied, uses \'sys.argv[1:]\'. If \'object\' is None or not supplied, creates a new OptionDummy object, stores option values there, and returns a tuple (args, object). If \'object\' is supplied, it is modified in place and \'getopt()\' just returns \'args\'; in both cases, the returned \'args\' is a modified copy of the passed-in \'args\' list, which is left untouched.'
def getopt(self, args=None, object=None):
if (args is None): args = sys.argv[1:] if (object is None): object = OptionDummy() created_object = 1 else: created_object = 0 self._grok_option_table() short_opts = string.join(self.short_opts) try: (opts, args) = getopt.getopt(args, short_opts, self.long_opts) except getopt.error as msg: raise DistutilsArgError, msg for (opt, val) in opts: if ((len(opt) == 2) and (opt[0] == '-')): opt = self.short2long[opt[1]] else: assert ((len(opt) > 2) and (opt[:2] == '--')) opt = opt[2:] alias = self.alias.get(opt) if alias: opt = alias if (not self.takes_arg[opt]): assert (val == ''), "boolean option can't have value" alias = self.negative_alias.get(opt) if alias: opt = alias val = 0 else: val = 1 attr = self.attr_name[opt] if (val and (self.repeat.get(attr) is not None)): val = (getattr(object, attr, 0) + 1) setattr(object, attr, val) self.option_order.append((opt, val)) if created_object: return (args, object) else: return args
'Returns the list of (option, value) tuples processed by the previous run of \'getopt()\'. Raises RuntimeError if \'getopt()\' hasn\'t been called yet.'
def get_option_order(self):
if (self.option_order is None): raise RuntimeError, "'getopt()' hasn't been called yet" else: return self.option_order
'Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object.'
def generate_help(self, header=None):
max_opt = 0 for option in self.option_table: long = option[0] short = option[1] l = len(long) if (long[(-1)] == '='): l = (l - 1) if (short is not None): l = (l + 5) if (l > max_opt): max_opt = l opt_width = (((max_opt + 2) + 2) + 2) line_width = 78 text_width = (line_width - opt_width) big_indent = (' ' * opt_width) if header: lines = [header] else: lines = ['Option summary:'] for option in self.option_table: (long, short, help) = option[:3] text = wrap_text(help, text_width) if (long[(-1)] == '='): long = long[0:(-1)] if (short is None): if text: lines.append((' --%-*s %s' % (max_opt, long, text[0]))) else: lines.append((' --%-*s ' % (max_opt, long))) else: opt_names = ('%s (-%s)' % (long, short)) if text: lines.append((' --%-*s %s' % (max_opt, opt_names, text[0]))) else: lines.append((' --%-*s' % opt_names)) for l in text[1:]: lines.append((big_indent + l)) return lines
'Create a new OptionDummy instance. The attributes listed in \'options\' will be initialized to None.'
def __init__(self, options=[]):
for opt in options: setattr(self, opt, None)
'Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use \'attrs\' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in \'attrs\' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the \'command_obj\' attribute to the empty dictionary; this will be filled in with real command objects by \'parse_command_line()\'.'
def __init__(self, attrs=None):
self.verbose = 1 self.dry_run = 0 self.help = 0 for attr in self.display_option_names: setattr(self, attr, 0) self.metadata = DistributionMetadata() for basename in self.metadata._METHOD_BASENAMES: method_name = ('get_' + basename) setattr(self, method_name, getattr(self.metadata, method_name)) self.cmdclass = {} self.command_packages = None self.script_name = None self.script_args = None self.command_options = {} self.dist_files = [] self.packages = None self.package_data = {} self.package_dir = None self.py_modules = None self.libraries = None self.headers = None self.ext_modules = None self.ext_package = None self.include_dirs = None self.extra_path = None self.scripts = None self.data_files = None self.password = '' self.command_obj = {} self.have_run = {} if attrs: options = attrs.get('options') if (options is not None): del attrs['options'] for (command, cmd_options) in options.items(): opt_dict = self.get_option_dict(command) for (opt, val) in cmd_options.items(): opt_dict[opt] = ('setup script', val) if ('licence' in attrs): attrs['license'] = attrs['licence'] del attrs['licence'] msg = "'licence' distribution option is deprecated; use 'license'" if (warnings is not None): warnings.warn(msg) else: sys.stderr.write((msg + '\n')) for (key, val) in attrs.items(): if hasattr(self.metadata, ('set_' + key)): getattr(self.metadata, ('set_' + key))(val) elif hasattr(self.metadata, key): setattr(self.metadata, key, val) elif hasattr(self, key): setattr(self, key, val) else: msg = ('Unknown distribution option: %s' % repr(key)) if (warnings is not None): warnings.warn(msg) else: sys.stderr.write((msg + '\n')) self.want_user_cfg = True if (self.script_args is not None): for arg in self.script_args: if (not arg.startswith('-')): break if (arg == '--no-user-cfg'): self.want_user_cfg = False break self.finalize_options()
'Get the option dictionary for a given command. If that command\'s option dictionary hasn\'t been created yet, then create it and return the new dictionary; otherwise, return the existing option dictionary.'
def get_option_dict(self, command):
dict = self.command_options.get(command) if (dict is None): dict = self.command_options[command] = {} return dict
'Find as many configuration files as should be processed for this platform, and return a list of filenames in the order in which they should be parsed. The filenames returned are guaranteed to exist (modulo nasty race conditions). There are three possible config files: distutils.cfg in the Distutils installation directory (ie. where the top-level Distutils __inst__.py file lives), a file in the user\'s home directory named .pydistutils.cfg on Unix and pydistutils.cfg on Windows/Mac; and setup.cfg in the current directory. The file in the user\'s home directory can be disabled with the --no-user-cfg option.'
def find_config_files(self):
files = [] check_environ() sys_dir = os.path.dirname(sys.modules['distutils'].__file__) sys_file = os.path.join(sys_dir, 'distutils.cfg') if os.path.isfile(sys_file): files.append(sys_file) if (os.name == 'posix'): user_filename = '.pydistutils.cfg' else: user_filename = 'pydistutils.cfg' if self.want_user_cfg: user_file = os.path.join(os.path.expanduser('~'), user_filename) if os.path.isfile(user_file): files.append(user_file) local_file = 'setup.cfg' if os.path.isfile(local_file): files.append(local_file) if DEBUG: self.announce(('using config files: %s' % ', '.join(files))) return files
'Parse the setup script\'s command line, taken from the \'script_args\' instance attribute (which defaults to \'sys.argv[1:]\' -- see \'setup()\' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the \'user_options\' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that \'options\' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line was successfully parsed and we should carry on with executing commands; false if no errors but we shouldn\'t execute commands (currently, this only happens if user asks for help).'
def parse_command_line(self):
toplevel_options = self._get_toplevel_options() self.commands = [] parser = FancyGetopt((toplevel_options + self.display_options)) parser.set_negative_aliases(self.negative_opt) parser.set_aliases({'licence': 'license'}) args = parser.getopt(args=self.script_args, object=self) option_order = parser.get_option_order() log.set_verbosity(self.verbose) if self.handle_display_options(option_order): return while args: args = self._parse_command_opts(parser, args) if (args is None): return if self.help: self._show_help(parser, display_options=(len(self.commands) == 0), commands=self.commands) return if (not self.commands): raise DistutilsArgError, 'no commands supplied' return 1
'Return the non-display options recognized at the top level. This includes options that are recognized *only* at the top level as well as options recognized for commands.'
def _get_toplevel_options(self):
return (self.global_options + [('command-packages=', None, 'list of packages that provide distutils commands')])
'Parse the command-line options for a single command. \'parser\' must be a FancyGetopt instance; \'args\' must be the list of arguments, starting with the current command (whose options we are about to parse). Returns a new version of \'args\' with the next command at the front of the list; will be the empty list if there are no more commands on the command line. Returns None if the user asked for help on this command.'
def _parse_command_opts(self, parser, args):
from distutils.cmd import Command command = args[0] if (not command_re.match(command)): raise SystemExit, ("invalid command name '%s'" % command) self.commands.append(command) try: cmd_class = self.get_command_class(command) except DistutilsModuleError as msg: raise DistutilsArgError, msg if (not issubclass(cmd_class, Command)): raise DistutilsClassError, ('command class %s must subclass Command' % cmd_class) if (not (hasattr(cmd_class, 'user_options') and isinstance(cmd_class.user_options, list))): raise DistutilsClassError, (('command class %s must provide ' + "'user_options' attribute (a list of tuples)") % cmd_class) negative_opt = self.negative_opt if hasattr(cmd_class, 'negative_opt'): negative_opt = negative_opt.copy() negative_opt.update(cmd_class.negative_opt) if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_options = fix_help_options(cmd_class.help_options) else: help_options = [] parser.set_option_table(((self.global_options + cmd_class.user_options) + help_options)) parser.set_negative_aliases(negative_opt) (args, opts) = parser.getopt(args[1:]) if (hasattr(opts, 'help') and opts.help): self._show_help(parser, display_options=0, commands=[cmd_class]) return if (hasattr(cmd_class, 'help_options') and isinstance(cmd_class.help_options, list)): help_option_found = 0 for (help_option, short, desc, func) in cmd_class.help_options: if hasattr(opts, parser.get_attr_name(help_option)): help_option_found = 1 if hasattr(func, '__call__'): func() else: raise DistutilsClassError(("invalid help function %r for help option '%s': must be a callable object (function, etc.)" % (func, help_option))) if help_option_found: return opt_dict = self.get_option_dict(command) for (name, value) in vars(opts).items(): opt_dict[name] = ('command line', value) return args
'Set final values for all the options on the Distribution instance, analogous to the .finalize_options() method of Command objects.'
def finalize_options(self):
for attr in ('keywords', 'platforms'): value = getattr(self.metadata, attr) if (value is None): continue if isinstance(value, str): value = [elm.strip() for elm in value.split(',')] setattr(self.metadata, attr, value)
'Show help for the setup script command-line in the form of several lists of command-line options. \'parser\' should be a FancyGetopt instance; do not expect it to be returned in the same state, as its option table will be reset to make it generate the correct help text. If \'global_options\' is true, lists the global options: --verbose, --dry-run, etc. If \'display_options\' is true, lists the "display-only" options: --name, --version, etc. Finally, lists per-command help for every command name or command class in \'commands\'.'
def _show_help(self, parser, global_options=1, display_options=1, commands=[]):
from distutils.core import gen_usage from distutils.cmd import Command if global_options: if display_options: options = self._get_toplevel_options() else: options = self.global_options parser.set_option_table(options) parser.print_help((self.common_usage + '\nGlobal options:')) print '' if display_options: parser.set_option_table(self.display_options) parser.print_help(('Information display options (just display ' + 'information, ignore any commands)')) print '' for command in self.commands: if (isinstance(command, type) and issubclass(command, Command)): klass = command else: klass = self.get_command_class(command) if (hasattr(klass, 'help_options') and isinstance(klass.help_options, list)): parser.set_option_table((klass.user_options + fix_help_options(klass.help_options))) else: parser.set_option_table(klass.user_options) parser.print_help(("Options for '%s' command:" % klass.__name__)) print '' print gen_usage(self.script_name)
'If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false.'
def handle_display_options(self, option_order):
from distutils.core import gen_usage if self.help_commands: self.print_commands() print '' print gen_usage(self.script_name) return 1 any_display_options = 0 is_display_option = {} for option in self.display_options: is_display_option[option[0]] = 1 for (opt, val) in option_order: if (val and is_display_option.get(opt)): opt = translate_longopt(opt) value = getattr(self.metadata, ('get_' + opt))() if (opt in ['keywords', 'platforms']): print ','.join(value) elif (opt in ('classifiers', 'provides', 'requires', 'obsoletes')): print '\n'.join(value) else: print value any_display_options = 1 return any_display_options
'Print a subset of the list of all commands -- used by \'print_commands()\'.'
def print_command_list(self, commands, header, max_length):
print (header + ':') for cmd in commands: klass = self.cmdclass.get(cmd) if (not klass): klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = '(no description available)' print (' %-*s %s' % (max_length, cmd, description))
'Print out a help message listing all available commands with a description of each. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute \'description\'.'
def print_commands(self):
import distutils.command std_commands = distutils.command.__all__ is_std = {} for cmd in std_commands: is_std[cmd] = 1 extra_commands = [] for cmd in self.cmdclass.keys(): if (not is_std.get(cmd)): extra_commands.append(cmd) max_length = 0 for cmd in (std_commands + extra_commands): if (len(cmd) > max_length): max_length = len(cmd) self.print_command_list(std_commands, 'Standard commands', max_length) if extra_commands: print self.print_command_list(extra_commands, 'Extra commands', max_length)
'Get a list of (command, description) tuples. The list is divided into "standard commands" (listed in distutils.command.__all__) and "extra commands" (mentioned in self.cmdclass, but not a standard command). The descriptions come from the command class attribute \'description\'.'
def get_command_list(self):
import distutils.command std_commands = distutils.command.__all__ is_std = {} for cmd in std_commands: is_std[cmd] = 1 extra_commands = [] for cmd in self.cmdclass.keys(): if (not is_std.get(cmd)): extra_commands.append(cmd) rv = [] for cmd in (std_commands + extra_commands): klass = self.cmdclass.get(cmd) if (not klass): klass = self.get_command_class(cmd) try: description = klass.description except AttributeError: description = '(no description available)' rv.append((cmd, description)) return rv
'Return a list of packages from which commands are loaded.'
def get_command_packages(self):
pkgs = self.command_packages if (not isinstance(pkgs, list)): if (pkgs is None): pkgs = '' pkgs = [pkg.strip() for pkg in pkgs.split(',') if (pkg != '')] if ('distutils.command' not in pkgs): pkgs.insert(0, 'distutils.command') self.command_packages = pkgs return pkgs
'Return the class that implements the Distutils command named by \'command\'. First we check the \'cmdclass\' dictionary; if the command is mentioned there, we fetch the class object from the dictionary and return it. Otherwise we load the command module ("distutils.command." + command) and fetch the command class from the module. The loaded class is also stored in \'cmdclass\' to speed future calls to \'get_command_class()\'. Raises DistutilsModuleError if the expected module could not be found, or if that module does not define the expected class.'
def get_command_class(self, command):
klass = self.cmdclass.get(command) if klass: return klass for pkgname in self.get_command_packages(): module_name = ('%s.%s' % (pkgname, command)) klass_name = command try: __import__(module_name) module = sys.modules[module_name] except ImportError: continue try: klass = getattr(module, klass_name) except AttributeError: raise DistutilsModuleError, ("invalid command '%s' (no class '%s' in module '%s')" % (command, klass_name, module_name)) self.cmdclass[command] = klass return klass raise DistutilsModuleError(("invalid command '%s'" % command))
'Return the command object for \'command\'. Normally this object is cached on a previous call to \'get_command_obj()\'; if no command object for \'command\' is in the cache, then we either create and return it (if \'create\' is true) or return None.'
def get_command_obj(self, command, create=1):
cmd_obj = self.command_obj.get(command) if ((not cmd_obj) and create): if DEBUG: self.announce(("Distribution.get_command_obj(): creating '%s' command object" % command)) klass = self.get_command_class(command) cmd_obj = self.command_obj[command] = klass(self) self.have_run[command] = 0 options = self.command_options.get(command) if options: self._set_command_options(cmd_obj, options) return cmd_obj
'Set the options for \'command_obj\' from \'option_dict\'. Basically this means copying elements of a dictionary (\'option_dict\') to attributes of an instance (\'command\'). \'command_obj\' must be a Command instance. If \'option_dict\' is not supplied, uses the standard option dictionary for this command (from \'self.command_options\').'
def _set_command_options(self, command_obj, option_dict=None):
command_name = command_obj.get_command_name() if (option_dict is None): option_dict = self.get_option_dict(command_name) if DEBUG: self.announce((" setting options for '%s' command:" % command_name)) for (option, (source, value)) in option_dict.items(): if DEBUG: self.announce((' %s = %s (from %s)' % (option, value, source))) try: bool_opts = map(translate_longopt, command_obj.boolean_options) except AttributeError: bool_opts = [] try: neg_opt = command_obj.negative_opt except AttributeError: neg_opt = {} try: is_string = isinstance(value, str) if ((option in neg_opt) and is_string): setattr(command_obj, neg_opt[option], (not strtobool(value))) elif ((option in bool_opts) and is_string): setattr(command_obj, option, strtobool(value)) elif hasattr(command_obj, option): setattr(command_obj, option, value) else: raise DistutilsOptionError, ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) except ValueError as msg: raise DistutilsOptionError, msg
'Reinitializes a command to the state it was in when first returned by \'get_command_obj()\': ie., initialized but not yet finalized. This provides the opportunity to sneak option values in programmatically, overriding or supplementing user-supplied values from the config files and command line. You\'ll have to re-finalize the command object (by calling \'finalize_options()\' or \'ensure_finalized()\') before using it for real. \'command\' should be a command name (string) or command object. If \'reinit_subcommands\' is true, also reinitializes the command\'s sub-commands, as declared by the \'sub_commands\' class attribute (if it has one). See the "install" command for an example. Only reinitializes the sub-commands that actually matter, ie. those whose test predicates return true. Returns the reinitialized command object.'
def reinitialize_command(self, command, reinit_subcommands=0):
from distutils.cmd import Command if (not isinstance(command, Command)): command_name = command command = self.get_command_obj(command_name) else: command_name = command.get_command_name() if (not command.finalized): return command command.initialize_options() command.finalized = 0 self.have_run[command_name] = 0 self._set_command_options(command) if reinit_subcommands: for sub in command.get_sub_commands(): self.reinitialize_command(sub, reinit_subcommands) return command
'Run each command that was seen on the setup script command line. Uses the list of commands found and cache of command objects created by \'get_command_obj()\'.'
def run_commands(self):
for cmd in self.commands: self.run_command(cmd)
'Do whatever it takes to run a command (including nothing at all, if the command has already been run). Specifically: if we have already created and run the command named by \'command\', return silently without doing anything. If the command named by \'command\' doesn\'t even have a command object yet, create one. Then invoke \'run()\' on that command object (or an existing one).'
def run_command(self, command):
if self.have_run.get(command): return log.info('running %s', command) cmd_obj = self.get_command_obj(command) cmd_obj.ensure_finalized() cmd_obj.run() self.have_run[command] = 1
'Reads the metadata values from a file object.'
def read_pkg_file(self, file):
msg = message_from_file(file) def _read_field(name): value = msg[name] if (value == 'UNKNOWN'): return None return value def _read_list(name): values = msg.get_all(name, None) if (values == []): return None return values metadata_version = msg['metadata-version'] self.name = _read_field('name') self.version = _read_field('version') self.description = _read_field('summary') self.author = _read_field('author') self.maintainer = None self.author_email = _read_field('author-email') self.maintainer_email = None self.url = _read_field('home-page') self.license = _read_field('license') if ('download-url' in msg): self.download_url = _read_field('download-url') else: self.download_url = None self.long_description = _read_field('description') self.description = _read_field('summary') if ('keywords' in msg): self.keywords = _read_field('keywords').split(',') self.platforms = _read_list('platform') self.classifiers = _read_list('classifier') if (metadata_version == '1.1'): self.requires = _read_list('requires') self.provides = _read_list('provides') self.obsoletes = _read_list('obsoletes') else: self.requires = None self.provides = None self.obsoletes = None
'Write the PKG-INFO file into the release tree.'
def write_pkg_info(self, base_dir):
pkg_info = open(os.path.join(base_dir, 'PKG-INFO'), 'w') try: self.write_pkg_file(pkg_info) finally: pkg_info.close()
'Write the PKG-INFO format data to a file object.'
def write_pkg_file(self, file):
version = '1.0' if (self.provides or self.requires or self.obsoletes): version = '1.1' self._write_field(file, 'Metadata-Version', version) self._write_field(file, 'Name', self.get_name()) self._write_field(file, 'Version', self.get_version()) self._write_field(file, 'Summary', self.get_description()) self._write_field(file, 'Home-page', self.get_url()) self._write_field(file, 'Author', self.get_contact()) self._write_field(file, 'Author-email', self.get_contact_email()) self._write_field(file, 'License', self.get_license()) if self.download_url: self._write_field(file, 'Download-URL', self.download_url) long_desc = rfc822_escape(self.get_long_description()) self._write_field(file, 'Description', long_desc) keywords = ','.join(self.get_keywords()) if keywords: self._write_field(file, 'Keywords', keywords) self._write_list(file, 'Platform', self.get_platforms()) self._write_list(file, 'Classifier', self.get_classifiers()) self._write_list(file, 'Requires', self.get_requires()) self._write_list(file, 'Provides', self.get_provides()) self._write_list(file, 'Obsoletes', self.get_obsoletes())
'Print \'msg\' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.'
def debug_print(self, msg):
from distutils.debug import DEBUG if DEBUG: print msg
'Select strings (presumably filenames) from \'self.files\' that match \'pattern\', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the \'fnmatch\' module: \'*\' and \'?\' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If \'anchor\' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If \'anchor\' is false, both of these will match. If \'prefix\' is supplied, then only filenames starting with \'prefix\' (itself a pattern) and ending with \'pattern\', with anything in between them, will match. \'anchor\' is ignored in this case. If \'is_regex\' is true, \'anchor\' and \'prefix\' are ignored, and \'pattern\' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return 1 if files are found.'
def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
files_found = 0 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) self.debug_print(("include_pattern: applying regex r'%s'" % pattern_re.pattern)) if (self.allfiles is None): self.findall() for name in self.allfiles: if pattern_re.search(name): self.debug_print((' adding ' + name)) self.files.append(name) files_found = 1 return files_found
'Remove strings (presumably filenames) from \'files\' that match \'pattern\'. Other parameters are the same as for \'include_pattern()\', above. The list \'self.files\' is modified in place. Return 1 if files are found.'
def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):
files_found = 0 pattern_re = translate_pattern(pattern, anchor, prefix, is_regex) self.debug_print(("exclude_pattern: applying regex r'%s'" % pattern_re.pattern)) for i in range((len(self.files) - 1), (-1), (-1)): if pattern_re.search(self.files[i]): self.debug_print((' removing ' + self.files[i])) del self.files[i] files_found = 1 return files_found
'Return list of registry keys.'
def read_keys(cls, base, key):
try: handle = RegOpenKeyEx(base, key) except RegError: return None L = [] i = 0 while True: try: k = RegEnumKey(handle, i) except RegError: break L.append(k) i += 1 return L
'Return dict of registry keys and values. All names are converted to lowercase.'
def read_values(cls, base, key):
try: handle = RegOpenKeyEx(base, key) except RegError: return None d = {} i = 0 while True: try: (name, value, type) = RegEnumValue(handle, i) except RegError: break name = name.lower() d[cls.convert_mbcs(name)] = cls.convert_mbcs(value) i += 1 return d
'Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, \'exe\'.'
def find_exe(self, exe):
for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn for p in os.environ['Path'].split(';'): fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn return exe
'Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, \'exe\'.'
def find_exe(self, exe):
for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn for p in string.split(os.environ['Path'], ';'): fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn return exe
'Get a list of devstudio directories (include, lib or path). Return a list of strings. The list will be empty if unable to access the registry or appropriate registry keys not found.'
def get_msvc_paths(self, path, platform='x86'):
if (not _can_read_reg): return [] path = (path + ' dirs') if (self.__version >= 7): key = ('%s\\%0.1f\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories' % (self.__root, self.__version)) else: key = ('%s\\6.0\\Build System\\Components\\Platforms\\Win32 (%s)\\Directories' % (self.__root, platform)) for base in HKEYS: d = read_values(base, key) if d: if (self.__version >= 7): return string.split(self.__macros.sub(d[path]), ';') else: return string.split(d[path], ';') if (self.__version == 6): for base in HKEYS: if (read_values(base, ('%s\\6.0' % self.__root)) is not None): self.warn('It seems you have Visual Studio 6 installed, but the expected registry settings are not present.\nYou must at least run the Visual Studio GUI once so that these entries are created.') break return []
'Set environment variable \'name\' to an MSVC path type value. This is equivalent to a SET command prior to execution of spawned commands.'
def set_path_env_var(self, name):
if (name == 'lib'): p = self.get_msvc_paths('library') else: p = self.get_msvc_paths(name) if p: os.environ[name] = string.join(p, ';')
'Parse a version predicate string.'
def __init__(self, versionPredicateStr):
versionPredicateStr = versionPredicateStr.strip() if (not versionPredicateStr): raise ValueError('empty package restriction') match = re_validPackage.match(versionPredicateStr) if (not match): raise ValueError(('bad package name in %r' % versionPredicateStr)) (self.name, paren) = match.groups() paren = paren.strip() if paren: match = re_paren.match(paren) if (not match): raise ValueError(('expected parenthesized list: %r' % paren)) str = match.groups()[0] self.pred = [splitUp(aPred) for aPred in str.split(',')] if (not self.pred): raise ValueError(('empty parenthesized list in %r' % versionPredicateStr)) else: self.pred = []
'True if version is compatible with all the predicates in self. The parameter version must be acceptable to the StrictVersion constructor. It may be either a string or StrictVersion.'
def satisfied_by(self, version):
for (cond, ver) in self.pred: if (not compmap[cond](version, ver)): return False return True
'Construct a new TextFile object. At least one of \'filename\' (a string) and \'file\' (a file-like object) must be supplied. They keyword argument options are described above and affect the values returned by \'readline()\'.'
def __init__(self, filename=None, file=None, **options):
if ((filename is None) and (file is None)): raise RuntimeError, "you must supply either or both of 'filename' and 'file'" for opt in self.default_options.keys(): if (opt in options): setattr(self, opt, options[opt]) else: setattr(self, opt, self.default_options[opt]) for opt in options.keys(): if (opt not in self.default_options): raise KeyError, ("invalid TextFile option '%s'" % opt) if (file is None): self.open(filename) else: self.filename = filename self.file = file self.current_line = 0 self.linebuf = []
'Open a new file named \'filename\'. This overrides both the \'filename\' and \'file\' arguments to the constructor.'
def open(self, filename):
self.filename = filename self.file = open(self.filename, 'r') self.current_line = 0
'Close the current file and forget everything we know about it (filename, current line number).'
def close(self):
self.file.close() self.file = None self.filename = None self.current_line = None
'Print (to stderr) a warning message tied to the current logical line in the current file. If the current logical line in the file spans multiple physical lines, the warning refers to the whole range, eg. "lines 3-5". If \'line\' supplied, it overrides the current line number; it may be a list or tuple to indicate a range of physical lines, or an integer for a single physical line.'
def warn(self, msg, line=None):
sys.stderr.write((('warning: ' + self.gen_error(msg, line)) + '\n'))
'Read and return a single logical line from the current file (or from an internal buffer if lines have previously been "unread" with \'unreadline()\'). If the \'join_lines\' option is true, this may involve reading multiple physical lines concatenated into a single string. Updates the current line number, so calling \'warn()\' after \'readline()\' emits a warning about the physical line(s) just read. Returns None on end-of-file, since the empty string can occur if \'rstrip_ws\' is true but \'strip_blanks\' is not.'
def readline(self):
if self.linebuf: line = self.linebuf[(-1)] del self.linebuf[(-1)] return line buildup_line = '' while 1: line = self.file.readline() if (line == ''): line = None if (self.strip_comments and line): pos = line.find('#') if (pos == (-1)): pass elif ((pos == 0) or (line[(pos - 1)] != '\\')): eol = (((line[(-1)] == '\n') and '\n') or '') line = (line[0:pos] + eol) if (line.strip() == ''): continue else: line = line.replace('\\#', '#') if (self.join_lines and buildup_line): if (line is None): self.warn('continuation line immediately precedes end-of-file') return buildup_line if self.collapse_join: line = line.lstrip() line = (buildup_line + line) if isinstance(self.current_line, list): self.current_line[1] = (self.current_line[1] + 1) else: self.current_line = [self.current_line, (self.current_line + 1)] else: if (line is None): return None if isinstance(self.current_line, list): self.current_line = (self.current_line[1] + 1) else: self.current_line = (self.current_line + 1) if (self.lstrip_ws and self.rstrip_ws): line = line.strip() elif self.lstrip_ws: line = line.lstrip() elif self.rstrip_ws: line = line.rstrip() if (((line == '') or (line == '\n')) and self.skip_blanks): continue if self.join_lines: if (line[(-1)] == '\\'): buildup_line = line[:(-1)] continue if (line[(-2):] == '\\\n'): buildup_line = (line[0:(-2)] + '\n') continue return line
'Read and return the list of all logical lines remaining in the current file.'
def readlines(self):
lines = [] while 1: line = self.readline() if (line is None): return lines lines.append(line)
'Push \'line\' (a string) onto an internal buffer that will be checked by future \'readline()\' calls. Handy for implementing a parser with line-at-a-time lookahead.'
def unreadline(self, line):
self.linebuf.append(line)
'Create and initialize a new Command object. Most importantly, invokes the \'initialize_options()\' method, which is the real initializer and depends on the actual command being instantiated.'
def __init__(self, dist):
from distutils.dist import Distribution if (not isinstance(dist, Distribution)): raise TypeError, 'dist must be a Distribution instance' if (self.__class__ is Command): raise RuntimeError, 'Command is an abstract class' self.distribution = dist self.initialize_options() self._dry_run = None self.verbose = dist.verbose self.force = None self.help = 0 self.finalized = 0
'Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, \'initialize_options()\' implementations are just a bunch of "self.foo = None" assignments. This method must be implemented by all command classes.'
def initialize_options(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if \'foo\' depends on \'bar\', then it is safe to set \'foo\' from \'bar\' as long as \'foo\' still has the same value it was assigned in \'initialize_options()\'. This method must be implemented by all command classes.'
def finalize_options(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'A command\'s raison d\'etre: carry out the action it exists to perform, controlled by the options initialized in \'initialize_options()\', customized by other commands, the setup script, the command-line, and config files, and finalized in \'finalize_options()\'. All terminal output and filesystem interaction should be done by \'run()\'. This method must be implemented by all command classes.'
def run(self):
raise RuntimeError, ('abstract method -- subclass %s must override' % self.__class__)
'If the current verbosity level is of greater than or equal to \'level\' print \'msg\' to stdout.'
def announce(self, msg, level=1):
log.log(level, msg)
'Print \'msg\' to stdout if the global DEBUG (taken from the DISTUTILS_DEBUG environment variable) flag is true.'
def debug_print(self, msg):
from distutils.debug import DEBUG if DEBUG: print msg sys.stdout.flush()
'Ensure that \'option\' is a string; if not defined, set it to \'default\'.'
def ensure_string(self, option, default=None):
self._ensure_stringlike(option, 'string', default)
'Ensure that \'option\' is a list of strings. If \'option\' is currently a string, we split it either on /,\s*/ or /\s+/, so "foo bar baz", "foo,bar,baz", and "foo, bar baz" all become ["foo", "bar", "baz"].'
def ensure_string_list(self, option):
val = getattr(self, option) if (val is None): return elif isinstance(val, str): setattr(self, option, re.split(',\\s*|\\s+', val)) else: if isinstance(val, list): ok = 1 for element in val: if (not isinstance(element, str)): ok = 0 break else: ok = 0 if (not ok): raise DistutilsOptionError, ("'%s' must be a list of strings (got %r)" % (option, val))
'Ensure that \'option\' is the name of an existing file.'
def ensure_filename(self, option):
self._ensure_tested_string(option, os.path.isfile, 'filename', "'%s' does not exist or is not a file")
'Set the values of any "undefined" options from corresponding option values in some other command object. "Undefined" here means "is None", which is the convention used to indicate that an option has not been changed between \'initialize_options()\' and \'finalize_options()\'. Usually called from \'finalize_options()\' for options that depend on some other command rather than another option of the same command. \'src_cmd\' is the other command from which option values will be taken (a command object will be created for it if necessary); the remaining arguments are \'(src_option,dst_option)\' tuples which mean "take the value of \'src_option\' in the \'src_cmd\' command object, and copy it to \'dst_option\' in the current command object".'
def set_undefined_options(self, src_cmd, *option_pairs):
src_cmd_obj = self.distribution.get_command_obj(src_cmd) src_cmd_obj.ensure_finalized() for (src_option, dst_option) in option_pairs: if (getattr(self, dst_option) is None): setattr(self, dst_option, getattr(src_cmd_obj, src_option))
'Wrapper around Distribution\'s \'get_command_obj()\' method: find (create if necessary and \'create\' is true) the command object for \'command\', call its \'ensure_finalized()\' method, and return the finalized command object.'
def get_finalized_command(self, command, create=1):
cmd_obj = self.distribution.get_command_obj(command, create) cmd_obj.ensure_finalized() return cmd_obj
'Run some other command: uses the \'run_command()\' method of Distribution, which creates and finalizes the command object if necessary and then invokes its \'run()\' method.'
def run_command(self, command):
self.distribution.run_command(command)
'Determine the sub-commands that are relevant in the current distribution (ie., that need to be run). This is based on the \'sub_commands\' class attribute: each tuple in that list may include a method that we call to determine if the subcommand needs to be run for the current distribution. Return a list of command names.'
def get_sub_commands(self):
commands = [] for (cmd_name, method) in self.sub_commands: if ((method is None) or method(self)): commands.append(cmd_name) return commands
'Copy a file respecting verbose, dry-run and force flags. (The former two default to whatever is in the Distribution object, and the latter defaults to false for commands that don\'t define it.)'
def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, (not self.force), link, dry_run=self.dry_run)
'Copy an entire directory tree respecting verbose, dry-run, and force flags.'
def copy_tree(self, infile, outfile, preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1):
return dir_util.copy_tree(infile, outfile, preserve_mode, preserve_times, preserve_symlinks, (not self.force), dry_run=self.dry_run)
'Move a file respecting dry-run flag.'
def move_file(self, src, dst, level=1):
return file_util.move_file(src, dst, dry_run=self.dry_run)
'Spawn an external command respecting dry-run flag.'
def spawn(self, cmd, search_path=1, level=1):
from distutils.spawn import spawn spawn(cmd, search_path, dry_run=self.dry_run)
'Special case of \'execute()\' for operations that process one or more input files and generate one output file. Works just like \'execute()\', except the operation is skipped and a different message printed if \'outfile\' already exists and is newer than all files listed in \'infiles\'. If the command defined \'self.force\', and it is true, then the command is unconditionally run -- does no timestamp checks.'
def make_file(self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1):
if (skip_msg is None): skip_msg = ('skipping %s (inputs unchanged)' % outfile) if isinstance(infiles, str): infiles = (infiles,) elif (not isinstance(infiles, (list, tuple))): raise TypeError, "'infiles' must be a string, or a list or tuple of strings" if (exec_msg is None): exec_msg = ('generating %s from %s' % (outfile, ', '.join(infiles))) if (self.force or dep_util.newer_group(infiles, outfile)): self.execute(func, args, exec_msg, level) else: log.debug(skip_msg)
'Return an HTTP request made via transport_class.'
def issue_request(self, transport_class):
transport = transport_class() proxy = xmlrpclib.ServerProxy('http://example.com/', transport=transport) try: proxy.pow(6, 8) except RuntimeError: return transport.fake_socket.getvalue() return None
'>>> print SampleClass(12).get() 12'
def __init__(self, val):
self.val = val
'>>> print SampleClass(12).double().get() 24'
def double(self):
return SampleClass((self.val + self.val))
'>>> print SampleClass(-5).get() -5'
def get(self):
return self.val
'>>> print SampleClass.a_staticmethod(10) 11'
def a_staticmethod(v):
return (v + 1)
'>>> print SampleClass.a_classmethod(10) 12 >>> print SampleClass(0).a_classmethod(10) 12'
def a_classmethod(cls, v):
return (v + 2)
'>>> print SampleClass.NestedClass().get() 0'
def __init__(self, val=0):
self.val = val
'>>> print SampleNewStyleClass(12).get() 12'
def __init__(self, val):
self.val = val
'>>> print SampleNewStyleClass(12).double().get() 24'
def double(self):
return SampleNewStyleClass((self.val + self.val))
'>>> print SampleNewStyleClass(-5).get() -5'
def get(self):
return self.val
'Runs gdb with the command line given by *args. Returns its stdout, stderr'
def run_gdb(self, *args):
(out, err) = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() return (out, err)
'Run \'python -c SOURCE\' under gdb with a breakpoint. Support injecting commands after the breakpoint is reached Returns the stdout from gdb cmds_after_breakpoint: if provided, a list of strings: gdb commands'
def get_stack_trace(self, source=None, script=None, breakpoint='PyObject_Print', cmds_after_breakpoint=None, import_site=False):
commands = ['set breakpoint pending yes', ('break %s' % breakpoint), 'run'] if cmds_after_breakpoint: commands += cmds_after_breakpoint else: commands += ['backtrace'] args = ['gdb', '--batch'] args += [('--eval-command=%s' % cmd) for cmd in commands] args += ['--args', sys.executable] if (not import_site): args += ['-S'] if source: args += ['-c', source] elif script: args += [script] (out, err) = self.run_gdb(*args) err = err.replace(('Function "%s" not defined.\n' % breakpoint), '') err = err.replace("warning: Unable to find libthread_db matching inferior's thread library, thread debugging will not be available.\n", '') err = err.replace('warning: Cannot initialize thread debugging library: Debugger service failed\n', '') self.assertEqual(err, '') return out