本文整理汇总了Python中inspect.getsourcefile方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getsourcefile方法的具体用法?Python inspect.getsourcefile怎么用?Python inspect.getsourcefile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getsourcefile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_modules
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules.keys():
lines, linen = inspect.getsourcelines(module)
counthash = { }
for linen,l in enumerate(lines):
linen += 1
m = fre.match(l)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning("%s:%d: Function %s redefined. Previously defined on line %d", filename,linen,name,prev)
# Get the start symbol
示例2: _makeAST
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def _makeAST(f):
# Need to look at the flags used to compile the original function f and
# pass these same flags to the compile() function. This ensures that
# syntax-changing __future__ imports like print_function work correctly.
orig_f_co_flags = f.__code__.co_flags
# co_flags can contain various internal flags that we can't pass to
# compile(), so strip them out here
valid_flags = 0
for future_feature in __future__.all_feature_names:
feature = getattr(__future__, future_feature)
valid_flags |= feature.compiler_flag
s = inspect.getsource(f)
s = _dedent(s)
# use compile instead of ast.parse so that additional flags can be passed
flags = ast.PyCF_ONLY_AST | (orig_f_co_flags & valid_flags)
tree = compile(s, filename='<unknown>', mode='exec',
flags=flags, dont_inherit=True)
# tree = ast.parse(s)
tree.sourcefile = inspect.getsourcefile(f)
tree.lineoffset = inspect.getsourcelines(f)[1] - 1
return tree
示例3: test_10_bench
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def test_10_bench(self):
import subprocess
#cmd = [sys.executable]
cmd = ['coverage', 'run']
p = subprocess.Popen(cmd+[
inspect.getsourcefile(run),
'--queue-maxsize=0',
'bench',
'--total=500'
], close_fds=True, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
stderr = utils.text(stderr)
print(stderr)
self.assertEqual(p.returncode, 0, stderr)
self.assertIn('Crawled', stderr)
self.assertIn('Fetched', stderr)
self.assertIn('Processed', stderr)
self.assertIn('Saved', stderr)
示例4: validate_modules
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def validate_modules(self):
# Match def p_funcname(
fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
for module in self.modules:
try:
lines, linen = inspect.getsourcelines(module)
except IOError:
continue
counthash = {}
for linen, line in enumerate(lines):
linen += 1
m = fre.match(line)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d',
filename, linen, name, prev)
# Get the start symbol
示例5: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def __init__(self, exc_type, exc_value, tb):
self.lineno = tb.tb_lineno
self.function_name = tb.tb_frame.f_code.co_name
self.locals = tb.tb_frame.f_locals
self.globals = tb.tb_frame.f_globals
fn = inspect.getsourcefile(tb) or inspect.getfile(tb)
if fn[-4:] in (".pyo", ".pyc"):
fn = fn[:-1]
# if it's a file on the file system resolve the real filename.
if os.path.isfile(fn):
fn = os.path.realpath(fn)
self.filename = to_unicode(fn, get_filesystem_encoding())
self.module = self.globals.get("__name__")
self.loader = self.globals.get("__loader__")
self.code = tb.tb_frame.f_code
# support for paste's traceback extensions
self.hide = self.locals.get("__traceback_hide__", False)
info = self.locals.get("__traceback_info__")
if info is not None:
info = to_unicode(info, "utf-8", "replace")
self.info = info
示例6: get_src_path
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def get_src_path(self, obj, append_base=True):
"""Creates a src path string with line info for use as markdown link.
"""
path = getsourcefile(obj)
if not self.src_root in path:
# this can happen with e.g.
# inlinefunc-wrapped functions
if hasattr(obj, "__module__"):
path = "%s.%s" % (obj.__module__, obj.__name__)
else:
path = obj.__name__
path = path.replace(".", "/")
pre, post = path.rsplit(self.src_root + "/", 1)
lineno = self.get_line_no(obj)
lineno = "" if lineno is None else "#L{}".format(lineno)
path = self.src_root + "/" + post + lineno
if append_base:
path = os.path.join(self.github_link, path)
return path
示例7: linkcode_resolve
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def linkcode_resolve(domain, info):
if domain != "py":
return None
if not info["module"]:
return None
mod = importlib.import_module(info["module"])
modpath = [p for p in sys.path if mod.__file__.startswith(p)]
if len(modpath) < 1:
raise RuntimeException("Cannot deduce module path")
modpath = modpath[0]
obj = reduce(getattr, [mod] + info["fullname"].split("."))
try:
path = inspect.getsourcefile(obj)
relpath = path[len(modpath) + 1 :]
_, lineno = inspect.getsourcelines(obj)
except TypeError:
# skip property or other type that inspect doesn't like
return None
return "http://github.com/scikit-hep/mplhep/blob/{}/{}#L{}".format(
githash, relpath, lineno
)
示例8: linkcode_resolve
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def linkcode_resolve(domain, info):
def find_line():
obj = sys.modules[info['module']]
for part in info['fullname'].split('.'):
obj = getattr(obj, part)
import inspect
fn = inspect.getsourcefile(obj)
source, lineno = inspect.findsource(obj)
return lineno + 1
if domain != 'py' or not info['module']:
return None
#tag = 'master' if 'dev' in release else ('v' + release)
url = "https://github.com/draios/python-sdc-client/blob/master/sdcclient/_client.py"
try:
return url + '#L%d' % find_line()
except Exception:
return url
示例9: add_fileline_to_docstring
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def add_fileline_to_docstring(module, incursive=True):
"""Append the definition position to each function contained in module.
Examples
--------
# Put the following codes at the end of a file
add_fileline_to_docstring(__name__)
"""
def _add_fileline(obj):
"""Add fileinto to a object.
"""
if obj.__doc__ is None or 'From:' in obj.__doc__:
return
fname = inspect.getsourcefile(obj)
if fname is None:
return
try:
line = inspect.getsourcelines(obj)[-1]
except IOError:
return
obj.__doc__ += '\n\nFrom:%s:%d' % (fname, line)
if isinstance(module, str):
module = sys.modules[module]
for _, obj in inspect.getmembers(module):
if inspect.isbuiltin(obj):
continue
if inspect.isfunction(obj):
_add_fileline(obj)
if inspect.ismethod(obj):
_add_fileline(obj.__func__)
if inspect.isclass(obj) and incursive:
add_fileline_to_docstring(obj, False)
示例10: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def __init__(self, cmd):
self.filename = inspect.getsourcefile(cmd)
source = inspect.getsourcelines(cmd)
self.line_number = source[1]
self.source = ''.join(source[0])
示例11: repl_format_source
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def repl_format_source(self, thing):
"""returns get_source formatted to be used in repl
rtfs originated as this alias:
debug (lambda cmd, bot=bot: (lambda f, out: out[0] if len(out) == 1 else (f(f,out[1:5] + (['{} more pages remaining..\njust tell them to read the actual source file man.'.format(len(out)-5)] if len(out) > 5 else [])) or out[0]))((lambda self, more: None if not more else bot.loop.create_task(bot.say('``'+'`py\n'+more.pop(0)+'``'+'`')).add_done_callback(self(self, more))), list(pagify((lambda ic, fc, pg: (lambda fcs: ic.getsourcefile(fc).split('/')[-1]+'\nline: {}'.format(fcs[1])+'``'+'`'+'\n'+'``'+'`py\n'+''.join(fcs[0]))(ic.getsourcelines(fc)))(__import__('inspect'), (cmd if not isinstance(cmd, str) else (lambda f, ms: f(f, __import__(ms.pop(0)), ms))((lambda f, prev, ms: getattr(prev, 'callback') if hasattr(prev, 'callback') else prev if not ms else f(f, getattr(prev, ms.pop(0)), ms)), cmd.split('.')) if '.' in cmd else (lambda end, cmds: end(end, cmds, bot.commands[cmds.pop(0)]).callback)((lambda end, names, cmd: cmd if not names else end(end, names, cmd.commands[names.pop(0)])), cmd.split()) ), __import__('cogs').utils.chat_formatting.pagify), delims=['\n', ' '], escape=False, shorten_by=12)) ))
"""
source = self.get_source(thing)
msg = source.filename.split('/')[-1] + '\n'
msg += 'line: {}'.format(source.line_number)
msg += '``'+'`\n`'+'``py\n' # codeblock break
msg += source.source
return msg
示例12: validate_module
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def validate_module(self, module):
lines, linen = inspect.getsourcelines(module)
fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(')
sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=')
counthash = { }
linen += 1
for l in lines:
m = fre.match(l)
if not m:
m = sre.match(l)
if m:
name = m.group(1)
prev = counthash.get(name)
if not prev:
counthash[name] = linen
else:
filename = inspect.getsourcefile(module)
self.log.error("%s:%d: Rule %s redefined. Previously defined on line %d",filename,linen,name,prev)
self.error = 1
linen += 1
# -----------------------------------------------------------------------------
# lex(module)
#
# Build all of the regular expression rules from definitions in the supplied module
# -----------------------------------------------------------------------------
示例13: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def __init__(self, func):
self.srcfile = inspect.getsourcefile(func)
self.srcline = inspect.getsourcelines(func)[0]
self.func = func
functools.update_wrapper(self, func)
self.calls = 0
self.name = None
# register the block
myhdl._simulator._blocks.append(self)
self.bound_functions = WeakValueDictionary()
示例14: _addUserCode
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def _addUserCode(specs, arg, funcname, func, frame):
classMap = {
'__verilog__': _UserVerilogCodeDepr,
'__vhdl__': _UserVhdlCodeDepr,
'verilog_code': _UserVerilogCode,
'vhdl_code': _UserVhdlCode,
'verilog_instance': _UserVerilogInstance,
'vhdl_instance': _UserVhdlInstance,
}
namespace = frame.f_globals.copy()
namespace.update(frame.f_locals)
sourcefile = inspect.getsourcefile(frame)
sourceline = inspect.getsourcelines(frame)[1]
for hdl in _userCodeMap:
oldspec = "__%s__" % hdl
codespec = "%s_code" % hdl
instancespec = "%s_instance" % hdl
spec = None
# XXX add warning logic
if instancespec in specs:
spec = instancespec
elif codespec in specs:
spec = codespec
elif oldspec in specs:
spec = oldspec
if spec:
assert id(arg) not in _userCodeMap[hdl]
code = specs[spec]
_userCodeMap[hdl][id(arg)] = classMap[spec](
code, namespace, funcname, func, sourcefile, sourceline)
示例15: __init__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getsourcefile [as 别名]
def __init__(self, fn):
self.fn = fn
self.filename = inspect.getsourcefile(fn)
self.sourcelines = {}
self.source = []
self.firstlineno = self.firstcodelineno = 0
try:
self.source, self.firstlineno = inspect.getsourcelines(fn)
self.firstcodelineno = self.firstlineno
self.find_source_lines()
except IOError:
self.filename = None