仅在键盘中断后进行回溯累积

2022-07-06 12:09:57 发布

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

这是我的代码:

import autopy
import time
import math
width, height = 400, 400
a, b = 200, 200
r = 150
def drawCicle():
    for x in range(0, 3):
        for angle in range(0, 360, 1):
            x = r * math.sin(math.radians(angle)) + a
            y = r * math.cos(math.radians(angle)) + b
            autopy.mouse.move(int(x),int(y))
            time.sleep(0.002)
def mouseMove():
    counter = 0
    while counter < 4:
        drawCicle()
        counter += 1
    else:
        print('Drawing ' + str(counter) + ' circles')
        print('moving once more in 10 seconds...')
        counter = 0
        time.sleep(10)
        mouseMove()

if __name__ == "__main__":
    mouseMove()

奇怪的是,代码运行得很好。我只有在用KeyboardInterrupt中断循环后才能得到回溯,从每个循环中溢出累积的回溯,循环如下:

Traceback (most recent call last):
  File "test.py", line 27, in <module>
    mouseMove()
  File "test.py", line 24, in mouseMove
    mouseMove()
  File "test.py", line 24, in mouseMove
    mouseMove()
  File "test.py", line 24, in mouseMove
    mouseMove()
  File "test.py", line 23, in mouseMove
    time.sleep(10)
KeyboardInterrupt

这种情况只有在我手动破解代码的情况下才会发生,有人能解释一下我忽略了什么样的最佳实践吗


Tags: 代码inpytestimporttimedeflinecountersleepmathfileangleautopymousemove
1条回答
网友
1楼 ·

如果要立即查看print语句的输出,只需使用^{}

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.


def mouseMove():
    counter = 0
    while counter < 4:
        drawCicle()
        counter += 1
    else:
        print('Drawing ' + str(counter) + ' circles', flush=True)
        print('moving once more in 10 seconds...', flush=True)
        counter = 0
        time.sleep(10)
        mouseMove()

只有当您带着异常退出程序时,才会打印异常回溯