Python可以生成类似于bash的setx的跟踪吗?

2024-10-03 19:29:56 发布

您现在位置:Python中文网/ 问答频道 /正文

Python中是否有类似的机制,就像set -x对bash的影响一样?在

下面是bash在这种模式下的一些输出示例:

+ for src in cpfs.c log.c popcnt.c ssse3_popcount.c blkcache.c context.c types.c device.c
++ my_mktemp blkcache.c.o
+++ mktemp -t blkcache.c.o.2160.XXX
++ p=/tmp/blkcache.c.o.2160.IKA
++ test 0 -eq 0
++ echo /tmp/blkcache.c.o.2160.IKA
+ obj=/tmp/blkcache.c.o.2160.IKA

我知道Python ^{}模块,但是它的输出似乎非常冗长,并且不像bash那样高级别。在


Tags: insrcbashlog示例for模式tmp
3条回答

要跟踪特定的调用,可以用自己的记录器包装每个有趣的函数。这会导致参数扩展为其值,而不仅仅是输出中的参数名。在

函数必须作为字符串传入,以防止模块重定向到其他模块的问题,例如操作系统路径/posixpath。我认为你不能仅仅从函数对象中提取正确的模块名来修补。在

包装代码:

import importlib

def wrapper(ffull, f):
    def logger(*args, **kwargs):
        print "TRACE: %s (%s, %s)" % (ffull, args, kwargs)
        return f(*args, **kwargs)
    return logger

def log_execution(ffull):
    parts = ffull.split('.')
    mname = '.'.join(parts[:-1])
    fname = parts[-1]
    m = importlib.import_module(mname)
    f = getattr(m, fname)
    setattr(m, fname, wrapper(ffull, f))

用法:

^{pr2}$

您应该尝试使用跟踪模块来获得更高的细节级别。 你到底需要什么?在

可能使用sys.settrace

使用traceit()打开跟踪,使用traceit(False)关闭跟踪。在

import sys
import linecache

def _traceit(frame, event, arg):
    '''
    http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html
    '''
    if event == "line":
        lineno = frame.f_lineno
        filename = frame.f_globals["__file__"]
        if (filename.endswith(".pyc") or
            filename.endswith(".pyo")):
            filename = filename[:-1]
        name = frame.f_globals["__name__"]
        line = linecache.getline(filename, lineno)
        print "%s  # %s:%s" % (line.rstrip(), name, lineno,)
    return _traceit

def _passit(frame, event, arg):
    return _passit

def traceit(on=True):
    if on: sys.settrace(_traceit)
    else: sys.settrace(_passit)

def mktemp(src):
    pass

def my_mktemp(src):
    mktemp(src)
    p=src

traceit()
for src in ('cpfs.c','log.c',):
    my_mktemp(src)
traceit(False)

收益率

^{pr2}$

相关问题 更多 >