加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python可以生成类似于bash的set -x的跟踪吗?

发布时间:2020-12-16 23:26:18 所属栏目:Python 来源:网络整理
导读:在 Python中是否有类似的机制,-b对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/
在 Python中是否有类似的机制,-b对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 trace模块,但它的输出似乎非常冗长,而不是像bash那样高级.

解决方法

也许使用 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,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)

产量

mktemp(src)  # __main__:33
pass  # __main__:30
p=src  # __main__:34
mktemp(src)  # __main__:33
pass  # __main__:30
p=src  # __main__:34
if on: sys.settrace(_traceit)  # __main__:26
else: sys.settrace(_passit)  # __main__:27

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读