采用 0 个位置参数,但给出 2 个位置参数,但情况并非如此

问题描述 投票:0回答:2

已解决,请在下面回答!

这是相关代码片段:

def redraw() -> int:
    subprocess.call(['tput', 'reset'])
    cursor.hide()
    print(get_time())
    return 0


def main() -> int:
    """
    Main function
    """
    time_between_updates = 0.5
    signal.signal(signal.SIGWINCH, redraw)

    old = ""
    while True:
        try:
            current = get_time()
            if old != current:
                redraw()
            old = get_time()
            time.sleep(time_between_updates)
        except KeyboardInterrupt:
            cursor.show()
            return 0

来自解释器的奇怪错误:

$: python3 .local/my_scripts/pytime

Traceback (most recent call last):
  File "/home/omega/.local/my_scripts/pytime", line 176, in <module>
    main()
  File "/home/omega/.local/my_scripts/pytime", line 169, in main
    time.sleep(time_between_updates)
TypeError: redraw() takes 0 positional arguments but 2 were given

突出显示的第 169 行:

time.sleep(time_between_updates)
甚至没有调用 redraw(),我可以确认整个文件中对 redraw() 的所有调用都是在没有参数的情况下完成的,与它的定义一致。

我真的不明白发生了什么。如果我能在这方面得到任何帮助,我很乐意。谢谢!

通过创建函数修复:

def redraw_wrapper(signum, frame):
    redraw()

并在行中使用它代替 redraw() :

-  signal.signal(signal.SIGWINCH, redraw)
+  signal.signal(signal.SIGWINCH, redraw_wrapper)

这样,当捕获 SIGWINCH 时就会调用 redraw_wrapper,但在任何其他情况下我仍然可以手动调用 redraw。

python arguments positional-argument
2个回答
1
投票

这里的罪魁祸首是:

signal.signal(signal.SIGWINCH, redraw)

查看文档这里了解具体原因,但我会在这里给您要点。

在编写信号处理程序时,由于中断是异步的,我们需要知道它来自哪里,以及它来自哪个线程(因为信号是在主线程中处理的),所以我们需要堆栈

frame

此外,一个信号处理程序可以处理多个信号,所有这些信号共享代码,但会在稍后的某个时刻分支,因此我们还需要确切地知道调用了哪个信号,我们将其称为

signum

因此,一般来说,所有用户定义的信号处理程序都需要接受

signum
frame

在我们的例子中,我们并不真正关心堆栈帧,也不关心符号,所以我们所要做的就是将定义更改为

def redraw(signum, frame)

你就可以出发了!


0
投票

更改为:

def redraw(signum, frame) -> int:
© www.soinside.com 2019 - 2024. All rights reserved.