6中不能正常工作吗

6中不能正常工作吗

本文介绍了是否执行"sys.settrace"在Python 3.5中可以正常工作,但在Python 3.6中不能正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试回答另一个问题时,我突然意识到,您可以在理论上不应该控制的情况下在线程中的任何时间运行代码.CPython有一个 settrace 函数,用于在一个人的代码中注册一个跟踪函数.为了通过使用类来检验这个想法,编写了以下代码.问题在于,似乎没有发生跟踪,并且在跟踪日志中没有生成任何数据.是什么原因导致下面显示的代码出现问题?

While trying to answer another question, it dawned on me that you can have code run any time in a thread when you theoretically should not have control. CPython has a settrace function for registering a tracing function in one's code. To test this idea from the use of a class, the following code was written. The problem is that tracing does not seem to occur, and no data is generated in the tracing log. What is causing the problem in the code shown below?

#! /usr/bin/env python3
import atexit
import collections
import pprint
import sys


def main():
    i = create_instance()
    print(len(i.data), flush=True)


def create_instance():
    instance = Tracer()
    return instance


class Tracer:

    def __init__(self):
        self.data = []
        sys.settrace(self.trace)
        atexit.register(pprint.pprint, self.data)
        atexit.register(sys.settrace, None)

    def trace(self, frame, event, arg):
        print('Tracing ...', flush=True)
        self.data.append(TraceRecord(frame, event, arg))
        return self.trace


TraceRecord = collections.namedtuple('TraceRecord', 'frame, event, arg')


if __name__ == '__main__':
    main()


附录:

在Windows上运行Python 3.5时,问题不明显.但是,在Python 3.6中不会发生跟踪,因此不会打印跟踪日志.如果有人可以将我的错误确认为一个恰当的答案,那么很有可能会接受该提交并给予赏金.

The problem is not apparent when running Python 3.5 on Windows. However, tracing does not occur in Python 3.6 such that the trace log is not printed. If someone can confirm the bug for me as a well-presented answer, there is a good chance the submission would be accepted and awarded the bounty.

推荐答案

我尝试了您的程序,并且确实如前所述,它没有任何可跟踪的内容.内置函数 print() len()不会生成跟踪事件,大概是因为它们是由平台定义的,并且假定它们的内部工作正常且没意思.

I tried your program, and indeed as posted it does not have anything to trace. The built-in functions print() and len() do not generate trace events, presumably since they are defined by the platform and it is assumed that their internals work correctly and are not interesting.

文档指出:

我修改了程序,以定义一个函数并调用它.当我这样做时,便会调用您的跟踪函数.

I modified your program to define a function and to call it. When I did this, then your trace function was called.

我定义的功能:

def doSomething():
  print("Hello World")

您的 main()函数的我的版本:

def main():
  i = create_instance()
  print(len(i.data))
  doSomething()
  print(len(i.data))

我看到的输出:

 0
 Tracing ...
 Tracing ...
 Hello World
 Tracing ...
 3

这篇关于是否执行"sys.settrace"在Python 3.5中可以正常工作,但在Python 3.6中不能正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 15:49