def __init__(self, code=None, text=None, filename=None): if code: self.code = code self.text = text else: if not text: assert filename, "If no code or text, need a filename" sourcef = open_source(filename) try: text = sourcef.read() finally: sourcef.close() self.text = text try: # Python 2.3 and 2.4 don't like partial last lines, so be sure # the text ends nicely for them. self.code = compile(text + '\n', filename, "exec") except SyntaxError: _, synerr, _ = sys.exc_info() raise NotPython( "Couldn't parse '%s' as Python source: '%s' at line %d" % (filename, synerr.msg, synerr.lineno) ) # Alternative Python implementations don't always provide all the # attributes on code objects that we need to do the analysis. for attr in ['co_lnotab', 'co_firstlineno', 'co_consts', 'co_code']: if not hasattr(self.code, attr): raise CoverageException( "This implementation of Python doesn't support code " "analysis.\n" "Run coverage.py under CPython for this command." )
def source_file(self): if os.path.exists(self.filename): return open_source(self.filename) source = self.file_locator.get_zip_data(self.filename) if source is not None: return StringIO(source) raise CoverageException("No source for code '%s'." % self.filename)
def __init__(self, code=None, text=None, filename=None): if code: self.code = code self.text = text else: if not text: sourcef = open_source(filename) try: text = sourcef.read() finally: sourcef.close() self.text = text try: self.code = compile(text + '\n', filename, 'exec') except SyntaxError: _, synerr, _ = sys.exc_info() raise NotPython( "Couldn't parse '%s' as Python source: '%s' at line %d" % (filename, synerr.msg, synerr.lineno)) for attr in ['co_lnotab', 'co_firstlineno', 'co_consts', 'co_code']: if not hasattr(self.code, attr): raise CoverageException( "This implementation of Python doesn't support code analysis.\nRun coverage.py under CPython for this command." )
def __init__(self, text=None, filename=None, exclude=None): """ Source can be provided as `text`, the text itself, or `filename`, from which the text will be read. Excluded lines are those that match `exclude`, a regex. """ self.filename = filename or '<code>' self.text = text if not self.text: try: sourcef = open_source(self.filename) try: self.text = sourcef.read() finally: sourcef.close() except IOError: _, err, _ = sys.exc_info() raise NoSource("No source for code: '%s': %s" % (self.filename, err)) if self.text and ord(self.text[0]) == 65279: self.text = self.text[1:] self.exclude = exclude self.show_tokens = False self.lines = self.text.split('\n') self.excluded = set() self.docstrings = set() self.classdefs = set() self.multiline = {} self.statement_starts = set() self._byte_parser = None
def __init__(self, text=None, filename=None, exclude=None): self.filename = filename or '<code>' self.text = text if not self.text: try: sourcef = open_source(self.filename) try: self.text = sourcef.read() finally: sourcef.close() except IOError: _, err, _ = sys.exc_info() raise NoSource("No source for code: '%s': %s" % (self.filename, err)) if self.text and ord(self.text[0]) == 65279: self.text = self.text[1:] self.exclude = exclude self.show_tokens = False self.lines = self.text.split('\n') self.excluded = set() self.docstrings = set() self.classdefs = set() self.multiline = {} self.statement_starts = set() self._byte_parser = None
def __init__(self, code = None, text = None, filename = None): if code: self.code = code self.text = text else: if not text: sourcef = open_source(filename) try: text = sourcef.read() finally: sourcef.close() self.text = text try: self.code = compile(text + '\n', filename, 'exec') except SyntaxError: _, synerr, _ = sys.exc_info() raise NotPython("Couldn't parse '%s' as Python source: '%s' at line %d" % (filename, synerr.msg, synerr.lineno)) for attr in ['co_lnotab', 'co_firstlineno', 'co_consts', 'co_code']: if not hasattr(self.code, attr): raise CoverageException("This implementation of Python doesn't support code analysis.\nRun coverage.py under CPython for this command.")
def __init__(self, text = None, filename = None, exclude = None): self.filename = filename or '<code>' self.text = text if not self.text: try: sourcef = open_source(self.filename) try: self.text = sourcef.read() finally: sourcef.close() except IOError: _, err, _ = sys.exc_info() raise NoSource("No source for code: '%s': %s" % (self.filename, err)) if self.text and ord(self.text[0]) == 65279: self.text = self.text[1:] self.exclude = exclude self.show_tokens = False self.lines = self.text.split('\n') self.excluded = set() self.docstrings = set() self.classdefs = set() self.multiline = {} self.statement_starts = set() self._byte_parser = None
def source_file(self): """Return an open file for reading the source of the code unit.""" if os.path.exists(self.filename): return open_source(self.filename) source = self.file_locator.get_zip_data(self.filename) if source is not None: return StringIO(source) raise CoverageException("No source for code '%s'." % self.filename)
def source_file(self): """Return an open file for reading the source of the code unit.""" if os.path.exists(self.filename): # A regular text file: open it. return open_source(self.filename) # Maybe it's in a zip file? source = self.file_locator.get_zip_data(self.filename) if source is not None: return StringIO(source) # Couldn't find source. raise CoverageException("No source for code %r." % self.filename)
def __init__(self, text=None, filename=None, exclude=None): """ Source can be provided as `text`, the text itself, or `filename`, from which the text will be read. Excluded lines are those that match `exclude`, a regex. """ assert text or filename, "CodeParser needs either text or filename" self.filename = filename or "<code>" self.text = text if not self.text: try: sourcef = open_source(self.filename) try: self.text = sourcef.read() finally: sourcef.close() except IOError: _, err, _ = sys.exc_info() raise NoSource( "No source for code: '%s': %s" % (self.filename, err) ) # Scrap the BOM if it exists. if self.text and ord(self.text[0]) == 0xfeff: self.text = self.text[1:] self.exclude = exclude self.show_tokens = False # The text lines of the parsed code. self.lines = self.text.split('\n') # The line numbers of excluded lines of code. self.excluded = set() # The line numbers of docstring lines. self.docstrings = set() # The line numbers of class definitions. self.classdefs = set() # A dict mapping line numbers to (lo,hi) for multi-line statements. self.multiline = {} # The line numbers that start statements. self.statement_starts = set() # Lazily-created ByteParser self._byte_parser = None
def make_code_from_py(filename): try: source_file = open_source(filename) except IOError: raise NoSource('No file to run: %r' % filename) try: source = source_file.read() finally: source_file.close() if not source or source[-1] != '\n': source += '\n' code = compile(source, filename, 'exec') return code
def run_python_file(filename, args, package=None): """Run a python file as if it were the main program on the command line. `filename` is the path to the file to execute, it need not be a .py file. `args` is the argument array to present as sys.argv, including the first element naming the file being executed. `package` is the name of the enclosing package, if any. """ # Create a module to serve as __main__ old_main_mod = sys.modules['__main__'] main_mod = imp.new_module('__main__') sys.modules['__main__'] = main_mod main_mod.__file__ = filename if package: main_mod.__package__ = package main_mod.__builtins__ = BUILTINS # Set sys.argv properly. old_argv = sys.argv sys.argv = args try: # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: source_file.close() # We have the source. `compile` still needs the last line to be clean, # so make sure it is, then compile a code object from it. if not source or source[-1] != '\n': source += '\n' code = compile(source, filename, "exec") # Execute the source file. exec_code_object(code, main_mod.__dict__) finally: # Restore the old __main__ sys.modules['__main__'] = old_main_mod # Restore the old argv and path sys.argv = old_argv
def make_code_from_py(filename): """Get source from `filename` and make a code object of it.""" # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: source_file.close() # We have the source. `compile` still needs the last line to be clean, # so make sure it is, then compile a code object from it. if not source or source[-1] != '\n': source += '\n' code = compile(source, filename, "exec") return code
def run_python_file(filename, args, package=None): """Run a python file as if it were the main program on the command line. `filename` is the path to the file to execute, it need not be a .py file. `args` is the argument array to present as sys.argv, including the first element naming the file being executed. `package` is the name of the enclosing package, if any. """ # Create a module to serve as __main__ old_main_mod = sys.modules['__main__'] main_mod = imp.new_module('__main__') sys.modules['__main__'] = main_mod main_mod.__file__ = filename if package: main_mod.__package__ = package main_mod.__builtins__ = BUILTINS # Set sys.argv and the first path element properly. old_argv = sys.argv old_path0 = sys.path[0] sys.argv = args if package: sys.path[0] = '' else: sys.path[0] = os.path.abspath(os.path.dirname(filename)) try: # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: source_file.close() # We have the source. `compile` still needs the last line to be clean, # so make sure it is, then compile a code object from it. if source[-1] != '\n': source += '\n' code = compile(source, filename, "exec") # Execute the source file. try: exec_code_object(code, main_mod.__dict__) except SystemExit: # The user called sys.exit(). Just pass it along to the upper # layers, where it will be handled. raise except: # Something went wrong while executing the user code. # Get the exc_info, and pack them into an exception that we can # throw up to the outer loop. We peel two layers off the traceback # so that the coverage.py code doesn't appear in the final printed # traceback. typ, err, tb = sys.exc_info() raise ExceptionDuringRun(typ, err, tb.tb_next.tb_next) finally: # Restore the old __main__ sys.modules['__main__'] = old_main_mod # Restore the old argv and path sys.argv = old_argv sys.path[0] = old_path0