如何使一个线程更新的字符串反映Python诅咒的变化?

时间:2019-01-03 08:00:33

标签: python terminal curses

我打算将<​​strong> curses 库实现到客户端的现有 Python 脚本中。该脚本将完全通过SSH运行。

我目前正在尝试模拟脚本将生成的某些输出。

在“水边测试”脚本中,我有3个变量:x,y,z。

我在curses循环旁边运行一个线程,该线程每x秒增加x,y和z。在循环中,我只是将三个变量打印到终端屏幕上。

问题:在我提供某种输入之前,变量不会更新。 如何使终端字符串自动更新值?

我正在Kubuntu的一个终端上对此进行测试。我尝试了Urwid并遇到了类似的问题。

import curses
import time
from threading import Thread

x, y, z = 0, 0, 0
go = True


def increment_ints():
    global x, y, z
    while go:
        x += 1
        y += 2
        z += 3
        time.sleep(3)


def main(screen):
    global go
    curses.initscr()
    screen.clear()
    while go:
        screen.addstr(0, 0, f"x: {x}, y = {y}, z = {z}")
        c = screen.getch()
        if c == ord('q'):
            go = False


if __name__ == '__main__':
    t = Thread(target=update_ints)
    t.setDaemon(True)
    t.start()
    curses.wrapper(main)

预期: 将显示x,y和z的值,它们反映了无需输入的增量。

实际结果: x,y和z的值分别保持为1、2和3,并且仅在按下键时才会更新。

----------- 编辑: 可以按预期工作:

import curses
import time
from threading import Thread

x, y, z = 0, 0, 0
go = True
def update_ints():
    global x, y, z
    x += 1
    y += 2
    z += 3


def main(screen):
    global go
    curses.initscr()
    screen.clear()
    while go:
        update_ints()
        screen.addstr(0, 0, f"x: {x}, y = {y}, z = {z}")
        c = screen.getch()
        if c == ord('q'):
            go = False
        time.sleep(3)


if __name__ == '__main__':
    curses.wrapper(main)

但是我需要从线程中更新值。

1 个答案:

答案 0 :(得分:0)

问题是c = screen.getch()阻塞了循环并阻止了值的更新。

正在移除...

c = screen.getch()
if c == ord('q'):
   go = False

...产生了预期的结果。

谢谢NEGR KITAEC