rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
os.setuid(nobody) except os.error: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) print scriptfile, script, decoded_query os.execve(scriptfile, [script, decoded_query], env) except: self.server.handle_error(self.request, self.client_address) os._exit(127)
try: sys.argv = [scriptfile] if '=' not in decoded_query: sys.argv.append(decoded_query) sys.stdout = self.wfile sys.stdin = self.rfile execfile(scriptfile, {"__name__": "__main__"}) finally: sys.argv = save_argv sys.stdin = save_stdin sys.stdout = save_stdout sys.stderr = save_stderr except SystemExit, sts: self.log_error("CGI script exit status %s", str(sts)) else: self.log_error("CGI script exited OK")
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = string.rfind(rest, '?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = string.find(rest, '/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return if not executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return nobody = nobody_uid() self.send_response(200, "Script output follows") self.wfile.flush() # Always flush before forking pid = os.fork() if pid != 0: # Parent pid, sts = os.waitpid(pid, 0) if sts: self.log_error("CGI script exit status x%x" % sts) return # Child try: # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html # XXX Much of the following could be prepared ahead of time! env = {} env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD'] = self.command uqrest = urllib.unquote(rest) env['PATH_INFO'] = uqrest env['PATH_TRANSLATED'] = self.translate_path(uqrest) env['SCRIPT_NAME'] = scriptname if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] # AUTH_TYPE # REMOTE_USER # REMOTE_IDENT if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in string.whitespace: accept.append(string.strip(line)) else: accept = accept + string.split(line[7:], ',') env['HTTP_ACCEPT'] = string.joinfields(accept, ',') ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = filter(None, self.headers.getheaders('cookie')) if co: env['HTTP_COOKIE'] = string.join(co, ', ') # XXX Other HTTP_* headers decoded_query = string.replace(query, '+', ' ') try: os.setuid(nobody) except os.error: pass os.dup2(self.rfile.fileno(), 0) os.dup2(self.wfile.fileno(), 1) print scriptfile, script, decoded_query os.execve(scriptfile, [script, decoded_query], env) except: self.server.handle_error(self.request, self.client_address) os._exit(127)
import pwd
try: import pwd except ImportError: return -1
def nobody_uid(): """Internal routine to get nobody's uid""" global nobody if nobody: return nobody import pwd try: nobody = pwd.getpwnam('nobody')[2] except KeyError: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) return nobody
pass
def __getitem__(self, index): return 2*tuple.__getitem__(self, index)
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unicode("123")]
pass
def __getitem__(self, index): return 2*str.__getitem__(self, index)
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unicode("123")]
tuple2: [(), (1,2,3)], str2: ["", "123"]
tuple2: {(): (), (1, 2, 3): (1, 2, 3)}, str2: {"": "", "123": "112233"}
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unicode("123")]
pass inputs[unicode2] = [unicode(), unicode("123")] for func in funcs: for (cls, inps) in inputs.iteritems(): for inp in inps: out = filter(func, cls(inp)) self.assertEqual(inp, out) self.assert_(not isinstance(out, cls))
def __getitem__(self, index): return 2*unicode.__getitem__(self, index) inputs[unicode2] = { unicode(): unicode(), unicode("123"): unicode("112233") } for (cls, inps) in inputs.iteritems(): for (inp, exp) in inps.iteritems(): self.assertEqual( filter(funcs[0], cls(inp)), filter(funcs[1], cls(inp)) ) for func in funcs: outp = filter(func, cls(inp)) self.assertEqual(outp, exp) self.assert_(not isinstance(outp, cls))
def test_filter_subclasses(self): # test, that filter() never returns tuple, str or unicode subclasses funcs = (None, lambda x: True) class tuple2(tuple): pass class str2(str): pass inputs = { tuple2: [(), (1,2,3)], str2: ["", "123"] } if have_unicode: class unicode2(unicode): pass inputs[unicode2] = [unicode(), unicode("123")]
z = zipfile.ZipFile(zip_filename, "wb",
z = zipfile.ZipFile(zip_filename, "w",
def visit (z, dirname, names): for name in names: path = os.path.normpath(os.path.join(dirname, name)) if os.path.isfile(path): z.write(path, path)
Optional keyword arg "name" gives the name of the file; by default use the file's name.
Optional keyword arg "name" gives the name of the test; by default use the file's basename.
def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the file; by default use the file's name. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if module_relative: package = _normalize_module(package) filename = _module_relative_path(package, filename) # If no name was given, then use the file's name. if name is None: name = os.path.split(filename)[-1] # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. s = open(filename).read() test = DocTestParser().get_doctest(s, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries
name = os.path.split(filename)[-1]
name = os.path.basename(filename)
def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the file; by default use the file's name. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if module_relative: package = _normalize_module(package) filename = _module_relative_path(package, filename) # If no name was given, then use the file's name. if name is None: name = os.path.split(filename)[-1] # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. s = open(filename).read() test = DocTestParser().get_doctest(s, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries
package The name of a Python package. Text-file paths will be interpreted relative to the directory containing this package. The package may be supplied as a package object or as a dotted package name.
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: package The name of a Python package. Text-file paths will be interpreted relative to the directory containing this package. The package may be supplied as a package object or as a dotted package name. setUp The name of a set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown The name of a tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite
The name of a set-up function. This is called before running the
A set-up function. This is called before running the
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: package The name of a Python package. Text-file paths will be interpreted relative to the directory containing this package. The package may be supplied as a package object or as a dotted package name. setUp The name of a set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown The name of a tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite
The name of a tear-down function. This is called after running the
A tear-down function. This is called after running the
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: package The name of a Python package. Text-file paths will be interpreted relative to the directory containing this package. The package may be supplied as a package object or as a dotted package name. setUp The name of a set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown The name of a tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite
name = os.path.split(path)[-1]
name = os.path.basename(path)
def DocFileTest(path, module_relative=True, package=None, globs=None, **options): if globs is None: globs = {} if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. if module_relative: package = _normalize_module(package) path = _module_relative_path(package, path) # Find the file and read it. name = os.path.split(path)[-1] doc = open(path).read() # Convert it to a test, and wrap it in a DocFileCase. test = DocTestParser().get_doctest(doc, globs, name, path, 0) return DocFileCase(test, **options)
The name of a set-up function. This is called before running the
A set-up function. This is called before running the
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp The name of a set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown The name of a tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ suite = unittest.TestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite
The name of a tear-down function. This is called after running the
A tear-down function. This is called after running the
def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp The name of a set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown The name of a tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ suite = unittest.TestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite
__builtin__.credits = _Printer("credits", "Python development is led by BeOpen PythonLabs (www.pythonlabs.com).")
if sys.platform[:4] == 'java': __builtin__.credits = _Printer( "credits", "Jython is maintained by the Jython developers (www.jython.org).") else: __builtin__.credits = _Printer("credits", """\ Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands for supporting Python development. See www.python.org for more information.""")
def __call__(self): self.__setup() prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break else: lineno += self.MAXLINES key = None while key is None: key = raw_input(prompt) if key not in ('', 'q'): key = None if key == 'q': break
ctype = msg.get_content_type() main, sub = ctype.split('/')
main = msg.get_content_maintype() sub = msg.get_content_subtype()
def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle_<maintype>_<subtype>(). If there's no handler for the # full MIME type, then dispatch to self._handle_<maintype>(). If # that's missing too, then dispatch to self._writeBody(). ctype = msg.get_content_type() # We do have a Content-Type: header. main, sub = ctype.split('/') specific = UNDERSCORE.join((main, sub)).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = main.replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg)
dict = readmodule_ex(module, path)
dict = _readmodule(module, path)
def readmodule(module, path=[]): '''Backwards compatible interface. Call readmodule_ex() and then only keep Class objects from the resulting dictionary.''' dict = readmodule_ex(module, path) res = {} for key, value in dict.items(): if isinstance(value, Class): res[key] = value return res
def readmodule_ex(module, path=[], inpackage=None):
def readmodule_ex(module, path=[]):
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
return _readmodule(module, path) def _readmodule(module, path, inpackage=None): '''Do the hard work for readmodule[_ex].'''
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
parent = readmodule_ex(package, path, inpackage)
parent = _readmodule(package, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
return readmodule_ex(submodule, parent['__path__'], package)
return _readmodule(submodule, parent['__path__'], package)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
classstack = []
stack = []
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
if token == 'def':
if tokentype == DEDENT:
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno)
if stack: cur_class = stack[-1][0] if isinstance(cur_class, Class): cur_class._addmethod(meth_name, lineno)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1]
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
dict[class_name] = cur_class classstack.append((cur_class, thisindent))
if not stack: dict[class_name] = cur_class stack.append((cur_class, thisindent))
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
readmodule_ex(mod, path)
_readmodule(mod, path)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
readmodule_ex(mod, path, inpackage)
_readmodule(mod, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
readmodule_ex(mod)
_readmodule(mod, [])
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
d = readmodule_ex(mod, path, inpackage)
d = _readmodule(mod, path, inpackage)
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
if n[0] != '_' and not n in dict:
if n[0] != '_':
def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class found in the module. If INPACKAGE is true, it must be the dotted name of the package in which we are searching for a submodule, and then PATH must be the package search path; otherwise, we are searching for a top-level module, and PATH is combined with sys.path. ''' # Compute the full module name (prepending inpackage if set) if inpackage: fullmodule = "%s.%s" % (inpackage, module) else: fullmodule = module # Check in the cache if fullmodule in _modules: return _modules[fullmodule] # Initialize the dict for this module's contents dict = {} # Check if it is a built-in module; we don't do much for these if module in sys.builtin_module_names and not inpackage: _modules[module] = dict return dict # Check for a dotted module name i = module.rfind('.') if i >= 0: package = module[:i] submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module f = None if inpackage: f, file, (suff, mode, type) = imp.find_module(module, path) else: f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path f, file, (suff, mode, type) = imp.find_module('__init__', [file]) _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] if classstack: # it's a class method cur_class = classstack[-1][0] cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # close all classes indented at least as much while classstack and \ classstack[-1][1] >= thisindent: del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() inherit = None if token == '(': names = [] # List of superclasses # there's a list of superclasses level = 1 super = [] # Tokens making up current superclass while True: tokentype, token, start, end, line = g.next() if token in (')', ',') and level == 1: n = "".join(super) if n in dict: # we know this super class n = dict[n] else: c = n.split('.') if len(c) > 1: # super class is of the form # module.class: look in module for # class m = c[-2] c = c[-1] if m in _modules: d = _modules[m] if c in d: n = d[c] names.append(n) if token == '(': level += 1 elif token == ')': level -= 1 if level == 0: break elif token == ',' and level == 1: pass else: super.append(token) inherit = names cur_class = Class(module, class_name, inherit, file, lineno) dict[class_name] = cur_class classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) for mod, mod2 in modules: try: # Recursively read the imported module if not inpackage: readmodule_ex(mod, path) else: try: readmodule_ex(mod, path, inpackage) except ImportError: readmodule_ex(mod) except: # If we can't find or parse the imported module, # too bad -- don't die here. pass elif token == 'from' and start[1] == 0: mod, token = _getname(g) if not mod or token != "import": continue names = _getnamelist(g) try: # Recursively read the imported module d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, # too bad -- don't die here. continue # add any classes that were defined in the imported module # to our name space if they were mentioned in the list for n, n2 in names: if n in d: dict[n2 or n] = d[n] elif n == '*': # only add a name if not already there (to mimic # what Python does internally) also don't add # names that start with _ for n in d: if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: pass f.close() return dict
gui = GUI(Tkinter.Tk()) Tkinter.mainloop()
root = Tkinter.Tk() try: gui = GUI(root) root.mainloop() finally: root.destroy()
def hide(self, event=None): self.stop() self.collapse()
curses.pair_content(curses.COLOR_PAIRS)
curses.pair_content(curses.COLOR_PAIRS - 1)
def module_funcs(stdscr): "Test module-level functions" for func in [curses.baudrate, curses.beep, curses.can_change_color, curses.cbreak, curses.def_prog_mode, curses.doupdate, curses.filter, curses.flash, curses.flushinp, curses.has_colors, curses.has_ic, curses.has_il, curses.isendwin, curses.killchar, curses.longname, curses.nocbreak, curses.noecho, curses.nonl, curses.noqiflush, curses.noraw, curses.reset_prog_mode, curses.termattrs, curses.termname, curses.erasechar, curses.getsyx]: func() # Functions that actually need arguments if curses.tigetstr("cnorm"): curses.curs_set(1) curses.delay_output(1) curses.echo() ; curses.echo(1) f = tempfile.TemporaryFile() stdscr.putwin(f) f.seek(0) curses.getwin(f) f.close() curses.halfdelay(1) curses.intrflush(1) curses.meta(1) curses.napms(100) curses.newpad(50,50) win = curses.newwin(5,5) win = curses.newwin(5,5, 1,1) curses.nl() ; curses.nl(1) curses.putp('abc') curses.qiflush() curses.raw() ; curses.raw(1) curses.setsyx(5,5) curses.setupterm(fd=sys.__stdout__.fileno()) curses.tigetflag('hc') curses.tigetnum('co') curses.tigetstr('cr') curses.tparm('cr') curses.typeahead(sys.__stdin__.fileno()) curses.unctrl('a') curses.ungetch('a') curses.use_env(1) # Functions only available on a few platforms if curses.has_colors(): curses.start_color() curses.init_pair(2, 1,1) curses.color_content(1) curses.color_pair(2) curses.pair_content(curses.COLOR_PAIRS) curses.pair_number(0) if hasattr(curses, 'use_default_colors'): curses.use_default_colors() if hasattr(curses, 'keyname'): curses.keyname(13) if hasattr(curses, 'has_key'): curses.has_key(13) if hasattr(curses, 'getmouse'): curses.mousemask(curses.BUTTON1_PRESSED) curses.mouseinterval(10)
pp_opts = _gen_preprocess_options (self.macros + macros, self.include_dirs + includes)
pp_opts = gen_preprocess_options (self.macros + macros, self.include_dirs + includes)
def compile (self, sources, macros=None, includes=None):
return self.object_filenames (sources)
def compile (self, sources, macros=None, includes=None):
lib_opts = _gen_lib_options (self.libraries + libraries, self.library_dirs + library_dirs)
lib_opts = gen_lib_options (self.libraries + libraries, self.library_dirs + library_dirs, "-l%s", "-L%s")
def link_shared_object (self, objects, output_filename, libraries=None, library_dirs=None, build_info=None):
def _gen_preprocess_options (macros, includes): pp_opts = [] for macro in macros: if len (macro) == 1: pp_opts.append ("-U%s" % macro[0]) elif len (macro) == 2: if macro[1] is None: pp_opts.append ("-D%s" % macro[0]) else: pp_opts.append ("-D%s=%s" % macro) for dir in includes: pp_opts.append ("-I%s" % dir) return pp_opts def _gen_lib_options (libraries, library_dirs): lib_opts = [] for dir in library_dirs: lib_opts.append ("-L%s" % dir) for lib in libraries: lib_opts.append ("-l%s" % lib) return lib_opts
def _split_command (cmd): """Split a command string up into the progam to run (a string) and the list of arguments; return them as (cmd, arglist).""" args = string.split (cmd) return (args[0], args[1:])
cmd = sys.argv[0]
cmd = os.path.basename(sys.argv[0])
def stopped(): print 'pydoc server stopped'
self.passiveserver = 0
self.passiveserver = 1
def connect(self, host = '', port = 0): '''Connect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port)''' if host: self.host = host if port: self.port = port self.passiveserver = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) self.file = self.sock.makefile('rb') self.welcome = self.getresp() return self.welcome
self.compiler = new_compiler (compiler=self.compiler,
self.compiler = new_compiler ( compiler="msvc",
def run (self):
self.precompile_hook()
def build_extensions (self):
self.prelink_hook()
if self.compiler.compiler_type == 'msvc': self.msvc_prelink_hack(sources, ext, extra_args)
def build_extensions (self):
def precompile_hook (self): pass def prelink_hook (self):
def msvc_prelink_hack (self, sources, ext, extra_args):
def find_swig (self): """Return the name of the SWIG executable. On Unix, this is just "swig" -- it should be in the PATH. Tries a bit harder on Windows. """
if self.compiler.compiler_type == 'msvc': def_file = ext.export_symbol_file if def_file is None: source_dir = os.path.dirname (sources[0]) ext_base = (string.split (ext.name, '.'))[-1] def_file = os.path.join (source_dir, "%s.def" % ext_base) if not os.path.exists (def_file): def_file = None if def_file is not None: extra_args.append ('/DEF:' + def_file) else: modname = string.split (ext.name, '.')[-1] extra_args.append('/export:init%s'%modname) implib_file = os.path.join ( self.build_temp, self.get_ext_libname (ext.name)) extra_args.append ('/IMPLIB:' + implib_file) self.mkpath (os.path.dirname (implib_file))
def_file = ext.export_symbol_file if def_file is None: source_dir = os.path.dirname (sources[0]) ext_base = (string.split (ext.name, '.'))[-1] def_file = os.path.join (source_dir, "%s.def" % ext_base) if not os.path.exists (def_file): def_file = None if def_file is not None: extra_args.append ('/DEF:' + def_file) else: modname = string.split (ext.name, '.')[-1] extra_args.append('/export:init%s' % modname) implib_file = os.path.join ( self.build_temp, self.get_ext_libname (ext.name)) extra_args.append ('/IMPLIB:' + implib_file) self.mkpath (os.path.dirname (implib_file))
def prelink_hook (self):
assert "invalid option tuple: %r" % (option,)
raise ValueError, "invalid option tuple: %r" % (option,)
def _grok_option_table (self): """Populate the various data structures that keep tabs on the option table. Called by 'getopt()' before it can do anything worthwhile. """ self.long_opts = [] self.short_opts = [] self.short2long.clear() self.repeat = {}
verify(tuple(a).__class__ is tuple)
def rev(self): if self._rev is not None: return self._rev L = list(self) L.reverse() self._rev = self.__class__(L) return self._rev
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None):
def __init__(self, s, charset=None, maxlinelen=None, header_name=None):
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
The maximum line length can either be specified by maxlinelen, or you can pass in the name of the header field (e.g. "Subject") to let this class guess the best line length to use to prevent wrapping. The default maxlinelen is 76.
The maximum line length can be specified explicitly via maxlinelen. You can also pass None for maxlinelen and the name of a header field (e.g. "Subject") to let the constructor guess the best line length to use. The default maxlinelen is 76.
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
self._maxlinelen = maxlinelen if header_name is not None: self.guess_maxlinelen(header_name)
if maxlinelen is None: if header_name is None: self._maxlinelen = MAXLINELEN else: self.guess_maxlinelen(header_name) else: self._maxlinelen = maxlinelen
def __init__(self, s, charset=None, maxlinelen=MAXLINELEN, header_name=None): """Create a MIME-compliant header that can contain many languages.
if charset.encoded_header_len(encoded) < self._maxlinelen:
elen = charset.encoded_header_len(encoded) if elen <= self._maxlinelen:
def _split(self, s, charset): # Split up a header safely for use with encode_chunks. BAW: this # appears to be a private convenience method. splittable = charset.to_splittable(s) encoded = charset.from_splittable(splittable) if charset.encoded_header_len(encoded) < self._maxlinelen: return [(encoded, charset)] else: # Divide and conquer. BAW: halfway depends on integer division. # When porting to Python 2.2, use the // operator. halfway = len(splittable) // 2 first = charset.from_splittable(splittable[:halfway], 0) last = charset.from_splittable(splittable[halfway:], 0) return self._split(first, charset) + self._split(last, charset)
halfway = len(splittable) // 2
halfway = _intdiv2(len(splittable))
def _split(self, s, charset): # Split up a header safely for use with encode_chunks. BAW: this # appears to be a private convenience method. splittable = charset.to_splittable(s) encoded = charset.from_splittable(splittable) if charset.encoded_header_len(encoded) < self._maxlinelen: return [(encoded, charset)] else: # Divide and conquer. BAW: halfway depends on integer division. # When porting to Python 2.2, use the // operator. halfway = len(splittable) // 2 first = charset.from_splittable(splittable[:halfway], 0) last = charset.from_splittable(splittable[halfway:], 0) return self._split(first, charset) + self._split(last, charset)
f="&xxx;" g='&
f="&xxx;" g='& i='x?a=b&c=d;' j='&amp;
def test_attr_values_entities(self): """Substitution of entities and charrefs in attribute values""" # SF bug #1452246 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; ' f="&xxx;" g='&#32;&#33;' h='&#500;' i='x?a=b&c=d;'>""", [("starttag", "a", [("b", "<"), ("c", "<>"), ("d", "&lt->"), ("e", "< "), ("f", "&xxx;"), ("g", " !"), ("h", "&#500;"), ("i", "x?a=b&c=d;"), ])])
("i", "x?a=b&c=d;"), ])])
("i", "x?a=b&c=d;"), ("j", "& ("k", "& ])])
def test_attr_values_entities(self): """Substitution of entities and charrefs in attribute values""" # SF bug #1452246 self.check_events("""<a b=&lt; c=&lt;&gt; d=&lt-&gt; e='&lt; ' f="&xxx;" g='&#32;&#33;' h='&#500;' i='x?a=b&c=d;'>""", [("starttag", "a", [("b", "<"), ("c", "<>"), ("d", "&lt->"), ("e", "< "), ("f", "&xxx;"), ("g", " !"), ("h", "&#500;"), ("i", "x?a=b&c=d;"), ])])
if not self.untagged_responses.has_key('READ-WRITE') \
if self.untagged_responses.has_key('READ-ONLY') \
def select(self, mailbox='INBOX', readonly=None): """Select a mailbox.
if self.untagged_responses.has_key('READ-WRITE') \ and self.untagged_responses.has_key('READ-ONLY'): del self.untagged_responses['READ-WRITE']
if self.untagged_responses.has_key('READ-ONLY') \ and not self.is_readonly:
def _command(self, name, *args):
def close(f):
def close(self):
def close(f): self.flush()
ok_builtin_modules = ('array', 'binascii', 'audioop', 'imageop', 'marshal', 'math', 'md5', 'parser', 'regex', 'rotor', 'select',
ok_builtin_modules = ('audioop', 'array', 'binascii', 'cmath', 'errno', 'imageop', 'marshal', 'math', 'md5', 'operator', 'parser', 'regex', 'rotor', 'select',
def reload(self, module, path=None): if path is None and hasattr(module, '__filename__'): head, tail = os.path.split(module.__filename__) path = [os.path.join(head, '')] return ihooks.ModuleImporter.reload(self, module, path)
def s_apply(self, func, *args, **kw):
def s_apply(self, func, args=(), kw=None):
def s_apply(self, func, *args, **kw):
r = apply(func, args, kw)
if kw: r = apply(func, args, kw) else: r = apply(func, args)
def s_apply(self, func, *args, **kw):
verify(cf.get('Long Line', 'foo', raw=1) == 'this line is much, much longer than my editor\nlikes it.') def write(src): print "Testing writing of files..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) output = StringIO.StringIO() cf.write(output) verify(output, """[DEFAULT] foo = another very long line [Long Line] foo = this line is much, much longer than my editor likes it. """)
def basic(src): print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() verify(L == [r'Commented Bar', r'Foo Bar', r'Internationalized Stuff', r'Section\with$weird%characters[' '\t', r'Spacey Bar', ], "unexpected list of section names") # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar') verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar') verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar') verify('__name__' not in cf.options("Foo Bar"), '__name__ "option" should not be exposed by the API!') # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: verify(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existance of option") verify(not cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") verify(not cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed")
"http://www.unicode.org/Public/UNIDATA/" + TESTDATAFILE)
"http://www.unicode.org/Public/3.2-Update/" + TESTDATAFILE)
def test_main(): if skip_expected: raise TestSkipped(TESTDATAFILE + " not found, download from " + "http://www.unicode.org/Public/UNIDATA/" + TESTDATAFILE) part1_data = {} for line in open(TESTDATAFILE): if '#' in line: line = line.split('#')[0] line = line.strip() if not line: continue if line.startswith("@Part"): part = line continue try: c1,c2,c3,c4,c5 = [unistr(x) for x in line.split(';')[:-1]] except RangeError: # Skip unsupported characters continue if verbose: print line # Perform tests verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line) verify(c4 == NFC(c4) == NFC(c5), line) verify(c3 == NFD(c1) == NFD(c2) == NFD(c3), line) verify(c5 == NFD(c4) == NFD(c5), line) verify(c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5), line) verify(c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5), line) # Record part 1 data if part == "@Part1": part1_data[c1] = 1 # Perform tests for all other data for c in range(sys.maxunicode+1): X = unichr(c) if X in part1_data: continue assert X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c
self._charset = 'iso-8859-1'
self._charset = None
def __init__(self, fp=None): self._info = {} self._charset = 'iso-8859-1' self._fallback = None if fp is not None: self._parse(fp)
if msg.find('\x00') >= 0: msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') if self._coerce: msgid1 = unicode(msgid1, self._charset) tmsg = [unicode(x, self._charset) for x in tmsg] for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: if self._coerce: msg = unicode(msg, self._charset) tmsg = unicode(tmsg, self._charset) catalog[msg] = tmsg
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<I', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II' else: raise IOError(0, 'Bad magic number', filename) # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] if msg.find('\x00') >= 0: # Plural forms msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') if self._coerce: msgid1 = unicode(msgid1, self._charset) tmsg = [unicode(x, self._charset) for x in tmsg] for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: if self._coerce: msg = unicode(msg, self._charset) tmsg = unicode(tmsg, self._charset) catalog[msg] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.splitlines(): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] elif k == 'plural-forms': v = v.split(';')
if mlen == 0 and tmsg.lower().startswith('project-id-version:'):
if mlen == 0:
def _parse(self, fp): """Override this method to support alternative .mo formats.""" unpack = struct.unpack filename = getattr(fp, 'name', '') # Parse the .mo file header, which consists of 5 little endian 32 # bit words. self._catalog = catalog = {} self.plural = lambda n: int(n != 1) # germanic plural by default buf = fp.read() buflen = len(buf) # Are we big endian or little endian? magic = unpack('<I', buf[:4])[0] if magic == self.LE_MAGIC: version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) ii = '<II' elif magic == self.BE_MAGIC: version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) ii = '>II' else: raise IOError(0, 'Bad magic number', filename) # Now put all messages from the .mo file buffer into the catalog # dictionary. for i in xrange(0, msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen if mend < buflen and tend < buflen: msg = buf[moff:mend] tmsg = buf[toff:tend] if msg.find('\x00') >= 0: # Plural forms msgid1, msgid2 = msg.split('\x00') tmsg = tmsg.split('\x00') if self._coerce: msgid1 = unicode(msgid1, self._charset) tmsg = [unicode(x, self._charset) for x in tmsg] for i in range(len(tmsg)): catalog[(msgid1, i)] = tmsg[i] else: if self._coerce: msg = unicode(msg, self._charset) tmsg = unicode(tmsg, self._charset) catalog[msg] = tmsg else: raise IOError(0, 'File is corrupt', filename) # See if we're looking at GNU .mo conventions for metadata if mlen == 0 and tmsg.lower().startswith('project-id-version:'): # Catalog description for item in tmsg.splitlines(): item = item.strip() if not item: continue k, v = item.split(':', 1) k = k.strip().lower() v = v.strip() self._info[k] = v if k == 'content-type': self._charset = v.split('charset=')[1] elif k == 'plural-forms': v = v.split(';')
k = match.end(0)
self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
def parse_starttag(self, i): rawdata = self.rawdata if shorttagopen.match(rawdata, i): # SGML shorthand: <tag/data/ == <tag>data</tag> # XXX Can data contain &... (entity or char refs)? # XXX Can data contain < or > (tag characters)? # XXX Can there be whitespace before the first /? match = shorttag.match(rawdata, i) if not match: return -1 tag, data = match.group(1, 2) tag = string.lower(tag) self.finish_shorttag(tag, data) k = match.end(0) return k # XXX The following should skip matching quotes (' or ") match = endbracket.search(rawdata, i+1) if not match: return -1 j = match.start(0) # Now parse the data between i+1 and j into a tag and attrs attrs = [] if rawdata[i:i+2] == '<>': # SGML shorthand: <> == <last open tag seen> k = j tag = self.lasttag else: match = tagfind.match(rawdata, i+1) if not match: raise RuntimeError, 'unexpected call to parse_starttag' k = match.end(0) tag = string.lower(rawdata[i+1:k]) self.lasttag = tag while k < j: match = attrfind.match(rawdata, k) if not match: break attrname, rest, attrvalue = match.group(1, 2, 3) if not rest: attrvalue = attrname elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] attrs.append((string.lower(attrname), attrvalue)) k = match.end(0) if rawdata[j] == '>': j = j+1 self.finish_starttag(tag, attrs) return j
import mimetools, StringIO headers = mimetools.Message(StringIO.StringIO( 'Content-Length: %d\n' % retrlen)) else: headers = noheaders()
headers += "Content-Length: %d\n" % retrlen headers = mimetools.Message(StringIO.StringIO(headers))
def open_ftp(self, url): """Use FTP protocol.""" host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = unquote(host) user = unquote(user or '') passwd = unquote(passwd or '') host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT else: port = int(port) path, attrs = splitattr(path) path = unquote(path) dirs = path.split('/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] if dirs and not dirs[0]: dirs[0] = '/' key = user, host, port, '/'.join(dirs) # XXX thread unsafe! if len(self.ftpcache) > MAXFTPCACHE: # Prune the cache, rather arbitrarily for k in self.ftpcache.keys(): if k != key: v = self.ftpcache[k] del self.ftpcache[k] v.close() try: if not self.ftpcache.has_key(key): self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if attr.lower() == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = value.upper() (fp, retrlen) = self.ftpcache[key].retrfile(file, type) if retrlen is not None and retrlen >= 0: import mimetools, StringIO headers = mimetools.Message(StringIO.StringIO( 'Content-Length: %d\n' % retrlen)) else: headers = noheaders() return addinfourl(fp, headers, "ftp:" + url) except ftperrors(), msg: raise IOError, ('ftp error', msg), sys.exc_info()[2]
del self._current_context[-1]
self._current_context = self._ns_contexts[-1] del self._ns_contexts[-1]
def endPrefixMapping(self, prefix): del self._current_context[-1]
class XMLFilterBase:
class XMLFilterBase(xmlreader.XMLReader):
def processingInstruction(self, target, data): self._out.write('<?%s %s?>' % (target, data))
def ignorableWhitespace(self, chars, start, end): self._cont_handler.ignorableWhitespace(chars, start, end)
def ignorableWhitespace(self, chars): self._cont_handler.ignorableWhitespace(chars)
def ignorableWhitespace(self, chars, start, end): self._cont_handler.ignorableWhitespace(chars, start, end)
f(1, 2, 3, *UserList([4, 5])
f(1, 2, 3, *UserList([4, 5]))
def h(j=1, a=2, h=3): print j, a, h
if keys:
if random.random() < 0.2: mutate = 0 while 1: newkey = Horrid(random.randrange(100)) if newkey not in target: break target[newkey] = Horrid(random.randrange(100)) keys.append(newkey) mutate = 1 elif keys:
def maybe_mutate(): if not mutate: return if random.random() < 0.5: return if random.random() < 0.5: target, keys = dict1, dict1keys else: target, keys = dict2, dict2keys if keys: i = random.randrange(len(keys)) key = keys[i] del target[key] # CAUTION: don't use keys.remove(key) here. Or do <wink>. The # point is that .remove() would trigger more comparisons, and so # also more calls to this routine. We're mutating often enough # without that. del keys[i]
vesion string using the format major.minor.build (or patchlevel).
version string using the format major.minor.build (or patchlevel).
def _norm_version(version,build=''): """ Normalize the version and build strings and return a single vesion string using the format major.minor.build (or patchlevel). """ l = string.split(version,'.') if build: l.append(build) try: ints = map(int,l) except ValueError: strings = l else: strings = map(str,ints) version = string.join(strings[:3],'.') return version
self.literal = 0
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: if self.__at_start: self.syntax_error('illegal data at start of file') self.__at_start = 0 data = rawdata[i:j] if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k self.literal = 0 continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:i], '\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise RuntimeError, 'only XML version 1.0 supported' if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') self.lineno = self.lineno + string.count(rawdata[i:k], '\n') i = k continue elif rawdata[i] == '&': res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + string.count(res.group(0), '\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.entitydefs.has_key(name): self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.syntax_error('reference to unknown entity') self.unknown_entityref(name) self.lineno = self.lineno + string.count(res.group(0), '\n') continue elif rawdata[i] == ']': if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise RuntimeError, 'neither < nor & ??' # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + string.count(data, '\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1])
if self.fp and not self._filePassed: self.fp.close() self.fp = None
self.close()
def __del__(self): """Call the "close()" method in case the user forgot.""" if self.fp and not self._filePassed: self.fp.close() self.fp = None
sys.stderr.write(py_exc.msg)
sys.stderr.write(py_exc.msg + '\n')
def compile(file, cfile=None, dfile=None, doraise=False): """Byte-compile one Python source file to Python bytecode. Arguments: file: source filename cfile: target filename; defaults to source with 'c' or 'o' appended ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) dfile: purported filename; defaults to source (this is the filename that will show up in error messages) doraise: flag indicating whether or not an exception should be raised when a compile error is found. If an exception occurs and this flag is set to False, a string indicating the nature of the exception will be printed, and the function will return to the caller. If an exception occurs and this flag is set to True, a PyCompileError exception will be raised. Note that it isn't necessary to byte-compile Python modules for execution efficiency -- Python itself byte-compiles a module when it is loaded, and if it can, writes out the bytecode to the corresponding .pyc (or .pyo) file. However, if a Python installation is shared between users, it is a good idea to byte-compile all modules upon installation, since other users may not be able to write in the source directories, and thus they won't be able to write the .pyc/.pyo file, and then they would be byte-compiling every module each time it is loaded. This can slow down program start-up considerably. See compileall.py for a script/module that uses this module to byte-compile all installed files (or all files in selected directories). """ f = open(file, 'U') try: timestamp = long(os.fstat(f.fileno()).st_mtime) except AttributeError: timestamp = long(os.stat(file).st_mtime) codestring = f.read() f.close() if codestring and codestring[-1] != '\n': codestring = codestring + '\n' try: codeobject = __builtin__.compile(codestring, dfile or file,'exec') except Exception,err: py_exc = PyCompileError(err.__class__,err.args,dfile or file) if doraise: raise py_exc else: sys.stderr.write(py_exc.msg) return if cfile is None: cfile = file + (__debug__ and 'c' or 'o') fc = open(cfile, 'wb') fc.write('\0\0\0\0') wr_long(fc, timestamp) marshal.dump(codeobject, fc) fc.flush() fc.seek(0, 0) fc.write(MAGIC) fc.close() set_creator_type(cfile)
all = self.db.guess_all_extensions('text/plain', strict=True) all.sort() eq(all, ['.bat', '.c', '.h', '.ksh', '.pl', '.txt'])
unless = self.failUnless all = Set(self.db.guess_all_extensions('text/plain', strict=True)) unless(all >= Set(['.bat', '.c', '.h', '.ksh', '.pl', '.txt']))
def test_guess_all_types(self): eq = self.assertEqual # First try strict all = self.db.guess_all_extensions('text/plain', strict=True) all.sort() eq(all, ['.bat', '.c', '.h', '.ksh', '.pl', '.txt']) # And now non-strict all = self.db.guess_all_extensions('image/jpg', strict=False) all.sort() eq(all, ['.jpg']) # And now for no hits all = self.db.guess_all_extensions('image/jpg', strict=True) eq(all, [])
'tk' + version )
lib_prefix + 'tk' + version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
'tcl' + version )
lib_prefix + 'tcl' + version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
if platform == 'cygwin': x11_inc = find_file('X11/Xlib.h', [], inc_dirs) if x11_inc is None: return
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
libs.append('tk'+version) libs.append('tcl'+version)
libs.append(lib_prefix + 'tk'+ version) libs.append(lib_prefix + 'tcl'+ version)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module.
elif 'r' in how: l_type = FCNTL.F_WRLCK
elif 'r' in how: l_type = FCNTL.F_RDLCK
def lock(self, how, *args):
\s+\w+\s+\w+ \s+\d+ [^/]*
[^/]*
def test_getstatus(self): # This pattern should match 'ls -ld /.' on any posix # system, however perversely configured. pat = r'''d......... # It is a directory. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. \s+\d+ # It has a size. [^/]* # Skip the date. /\. # and end with the name of the file. '''
import _winreg from _winreg import HKEY_LOCAL_MACHINE try: pathname = _winreg.QueryValueEx(HKEY_LOCAL_MACHINE, \ "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, name)) fp = open(pathname, "rb") stuff = "", "rb", imp.C_EXTENSION return fp, pathname, stuff except _winreg.error: pass
result = _try_registry(name) if result: return result
def find_module(self, name, path): if name in self.excludes: self.msgout(3, "find_module -> Excluded") raise ImportError, name
self.stacksize = findDepth(self.insts)
def flattenGraph(self): """Arrange the blocks in order and resolve jumps""" assert self.stage == RAW self.insts = insts = [] pc = 0 begin = {} end = {} for b in self.getBlocksInOrder(): begin[b] = pc for inst in b.getInstructions(): insts.append(inst) if len(inst) == 1: pc = pc + 1 else: # arg takes 2 bytes pc = pc + 3 end[b] = pc pc = 0 for i in range(len(insts)): inst = insts[i] if len(inst) == 1: pc = pc + 1 else: pc = pc + 3 opname = inst[0] if self.hasjrel.has_elt(opname): oparg = inst[1] offset = begin[oparg] - pc insts[i] = opname, offset elif self.hasjabs.has_elt(opname): insts[i] = opname, begin[inst[1]] self.stacksize = findDepth(self.insts) self.stage = FLAT
def findDepth(self, insts):
def findDepth(self, insts, debug=0):
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta == 0: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth < 0: depth = 0 return maxDepth
delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth
if debug: print i, delta = self.effect.get(opname, None) if delta is not None:
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta == 0: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth < 0: depth = 0 return maxDepth
if depth > maxDepth: maxDepth = depth
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta == 0: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth < 0: depth = 0 return maxDepth
if delta == 0:
if delta is None:
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta == 0: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth < 0: depth = 0 return maxDepth
if depth < 0: depth = 0
if depth > maxDepth: maxDepth = depth if debug: print depth, maxDepth
def findDepth(self, insts): depth = 0 maxDepth = 0 for i in insts: opname = i[0] delta = self.effect.get(opname, 0) if delta > 1: depth = depth + delta elif delta < 0: if depth > maxDepth: maxDepth = depth depth = depth + delta else: if depth > maxDepth: maxDepth = depth # now check patterns for pat, pat_delta in self.patterns: if opname[:len(pat)] == pat: delta = pat_delta depth = depth + delta break # if we still haven't found a match if delta == 0: meth = getattr(self, opname, None) if meth is not None: depth = depth + meth(i[1]) if depth < 0: depth = 0 return maxDepth
return lo + hi * 2
return -(lo + hi * 2)
def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return lo + hi * 2
return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)-1
def CALL_FUNCTION_VAR(self, argc): return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)-1
def CALL_FUNCTION_KW(self, argc): return self.CALL_FUNCTION(argc)+1
return self.CALL_FUNCTION(argc)+2
return self.CALL_FUNCTION(argc)-2
def CALL_FUNCTION_VAR_KW(self, argc): return self.CALL_FUNCTION(argc)+2
self.file.write(delim + line)
self.file.write(odelim + line)
def read_lines_to_outerboundary(self):
displayname = linkname = name = cgi.escape(name)
displayname = linkname = name
def list_directory(self, path): """Helper to produce a directory listing (absent index.html).
f.write('<li><a href="%s">%s</a>\n' % (linkname, displayname))
f.write('<li><a href="%s">%s</a>\n' % (urllib.quote(linkname), cgi.escape(displayname)))
def list_directory(self, path): """Helper to produce a directory listing (absent index.html).
return id(self)
return hash(id(self))
def __hash__(self, *args): print "__hash__:", args return id(self)
>>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF |
>>> import doctest >>> old = doctest._unittest_reportflags >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old
>>> import doctest
def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old