我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.findsource()。
def introspect_docstring_lineno(api_doc): """ Try to determine the line number on which the given item's docstring begins. Return the line number, or C{None} if the line number can't be determined. The line number of the first line in the file is 1. """ if api_doc.docstring_lineno is not UNKNOWN: return api_doc.docstring_lineno if isinstance(api_doc, ValueDoc) and api_doc.pyval is not UNKNOWN: try: lines, lineno = inspect.findsource(api_doc.pyval) if not isinstance(api_doc, ModuleDoc): lineno += 1 for lineno in range(lineno, len(lines)): if lines[lineno].split('#', 1)[0].strip(): api_doc.docstring_lineno = lineno + 1 return lineno + 1 except IOError: pass except TypeError: pass except IndexError: log.warning('inspect.findsource(%s) raised IndexError' % api_doc.canonical_name) return None
def _printlonglist(self, linerange=None): try: if self.curframe.f_code.co_name == '<module>': # inspect.getsourcelines is buggy in this case: if we just # pass the frame, it returns the source for the first function # defined in the module. Instead, we want the full source # code of the module lines, _ = inspect.findsource(self.curframe) lineno = 1 else: try: lines, lineno = inspect.getsourcelines(self.curframe) except Exception as e: print('** Error in inspect.getsourcelines: %s **' % e, file=self.stdout) return except IOError as e: print('** Error: %s **' % e, file=self.stdout) return if linerange: start, end = linerange start = max(start, lineno) end = min(end, lineno+len(lines)) lines = lines[start-lineno:end-lineno] lineno = start self._print_lines_pdbpp(lines, lineno)
def with_patch_inspect(f): """ Deprecated since IPython 6.0 decorator for monkeypatching inspect.findsource """ def wrapped(*args, **kwargs): save_findsource = inspect.findsource save_getargs = inspect.getargs inspect.findsource = findsource inspect.getargs = getargs try: return f(*args, **kwargs) finally: inspect.findsource = save_findsource inspect.getargs = save_getargs return wrapped
def _number_of_line(member): """Try to return the number of the first line of the definition of a member of a module.""" if isinstance(member, tuple): member = member[1] try: return member.__code__.co_firstlineno except AttributeError: pass try: return inspect.findsource(member)[1] except BaseException: pass for (key, value) in vars(member).items(): try: return value.__code__.co_firstlineno except AttributeError: pass else: return 0
def get_current_frame_data(self): """ Get all date about the current execution frame :return: current frame data :rtype: dict :raises AttributeError: if the debugger does hold any execution frame. :raises IOError: if source code for the current execution frame is not accessible. """ filename = self.curframe.f_code.co_filename lines, start_line = inspect.findsource(self.curframe) if sys.version_info[0] == 2: lines = [line.decode('utf-8') for line in lines] return { 'filename': os.path.basename(filename), 'listing': ''.join(lines), 'curr_line': self.curframe.f_lineno, 'total_lines': len(lines), 'breaklist': self.get_file_breaks(filename), }
def GetFileAndLine(component): """Returns the filename and line number of component. Args: component: A component to find the source information for, usually a class or routine. Returns: filename: The name of the file where component is defined. lineno: The line number where component is defined. """ if inspect.isbuiltin(component): return None, None try: filename = inspect.getsourcefile(component) except TypeError: return None, None try: unused_code, lineindex = inspect.findsource(component) lineno = lineindex + 1 except IOError: lineno = None return filename, lineno
def test_getfslineno(): from py.code import getfslineno def f(x): pass fspath, lineno = getfslineno(f) assert fspath.basename == "test_source.py" assert lineno == py.code.getrawcode(f).co_firstlineno-1 # see findsource class A(object): pass fspath, lineno = getfslineno(A) _, A_lineno = inspect.findsource(A) assert fspath.basename == "test_source.py" assert lineno == A_lineno assert getfslineno(3) == ("", -1) class B: pass B.__name__ = "B2" assert getfslineno(B)[1] == -1
def getsourcelines(self, obj): lines, lineno = inspect.findsource(obj) if inspect.isframe(obj) and obj.f_globals is obj.f_locals: # must be a module frame: do not try to cut a block out of it return lines, 1 elif inspect.ismodule(obj): return lines, 1 return inspect.getblock(lines[lineno:]), lineno+1
def getsourcelines(obj): lines, lineno = inspect.findsource(obj) if inspect.isframe(obj) and obj.f_globals is obj.f_locals: # must be a module frame: do not try to cut a block out of it return lines, 1 elif inspect.ismodule(obj): return lines, 1 return inspect.getblock(lines[lineno:]), lineno+1
def test_findsource_binary(self): self.assertRaises(IOError, inspect.getsource, unicodedata) self.assertRaises(IOError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(IOError, inspect.findsource, co) self.assertRaises(IOError, inspect.getsource, co) linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) self.assertEqual(inspect.findsource(co), (lines,0)) self.assertEqual(inspect.getsource(co), lines[0])
def _class_get_line(clss): return inspect.findsource(clss)[1]
def test_findsource_without_filename(self): for fname in ['', '<string>']: co = compile('x=1', fname, "exec") self.assertRaises(IOError, inspect.findsource, co) self.assertRaises(IOError, inspect.getsource, co)
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(IOError, inspect.findsource, co) self.assertRaises(IOError, inspect.getsource, co) linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) try: self.assertEqual(inspect.findsource(co), (lines,0)) self.assertEqual(inspect.getsource(co), lines[0]) finally: del linecache.cache[co.co_filename]
def Info(component): """Returns a dict with information about the given component. The dict will have at least some of the following fields. type_name: The type of `component`. string_form: A string representation of `component`. file: The file in which `component` is defined. line: The line number at which `component` is defined. docstring: The docstring of `component`. init_docstring: The init docstring of `component`. class_docstring: The class docstring of `component`. call_docstring: The call docstring of `component`. length: The length of `component`. Args: component: The component to analyze. Returns: A dict with information about the component. """ try: from IPython.core import oinspect # pylint: disable=g-import-not-at-top inspector = oinspect.Inspector() info = inspector.info(component) except ImportError: info = _InfoBackup(component) try: unused_code, lineindex = inspect.findsource(component) info['line'] = lineindex + 1 except (TypeError, IOError): info['line'] = None return info
def with_patch_inspect(f): """decorator for monkeypatching inspect.findsource""" def wrapped(*args, **kwargs): save_findsource = inspect.findsource save_getargs = inspect.getargs inspect.findsource = findsource inspect.getargs = getargs try: return f(*args, **kwargs) finally: inspect.findsource = save_findsource inspect.getargs = save_getargs return wrapped
def test_findsource_binary(self): self.assertRaises(OSError, inspect.getsource, unicodedata) self.assertRaises(OSError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self): lines = ["x=1"] co = compile(lines[0], "_dynamically_created_file", "exec") self.assertRaises(OSError, inspect.findsource, co) self.assertRaises(OSError, inspect.getsource, co) linecache.cache[co.co_filename] = (1, None, lines, co.co_filename) try: self.assertEqual(inspect.findsource(co), (lines,0)) self.assertEqual(inspect.getsource(co), lines[0]) finally: del linecache.cache[co.co_filename]
def getsourcelines(obj): obj = _unwrap(obj) lines, lnum = inspect.findsource(obj) if inspect.ismodule(obj): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
def getfslineno(obj): """ Return source location (path, lineno) for the given object. If the source cannot be determined return ("", -1) """ try: code = py.code.Code(obj) except TypeError: try: fn = (inspect.getsourcefile(obj) or inspect.getfile(obj)) except TypeError: return "", -1 fspath = fn and py.path.local(fn) or None lineno = -1 if fspath: try: _, lineno = findsource(obj) except IOError: pass else: fspath = code.path lineno = code.firstlineno assert isinstance(lineno, int) return fspath, lineno # # helper functions #
def findsource(obj): try: sourcelines, lineno = inspect.findsource(obj) except py.builtin._sysex: raise except: return None, -1 source = Source() source.lines = [line.rstrip() for line in sourcelines] return source, lineno
def test_findsource_fallback(): from py._code.source import findsource src, lineno = findsource(x) assert 'test_findsource_simple' in str(src) assert src[lineno] == ' def x():'
def test_findsource(): from py._code.source import findsource co = py.code.compile("""if 1: def x(): pass """) src, lineno = findsource(co) assert 'if 1:' in str(src) d = {} eval(co, d) src, lineno = findsource(d['x']) assert 'if 1:' in str(src) assert src[lineno] == " def x():"
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except: return None try: fn = inspect.getsourcefile(obj) except: fn = None if not fn: return None try: source, lineno = inspect.findsource(obj) except: lineno = None if lineno: linespec = "#L%d" % (lineno + 1) else: linespec = "" fn = relpath(fn, start='..') return "https://github.com/mithrandi/txacme/blob/%s/%s%s" % ( txacme_version_info['full-revisionid'], fn, linespec)
def findsource(obj): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" filename = inspect.getsourcefile(obj) if filename: linecache.checkcache(filename) return inspect.findsource(obj)