简体   繁体   English

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

[英]How can I made a string that is updated by a thread reflect the changes on Python's curses?

I am planning to implement the curses library into an existing Python script for a client.我计划将curses库实现到客户端的现有Python脚本中。 The script will be run purely through SSH.该脚本将完全通过 SSH 运行。

I am currently attempting to simulate some of the output that my script would generate.我目前正在尝试模拟我的脚本将生成的一些输出。

In my 'testing-the-waters' script I have 3 variables: x, y, z.在我的“试水”脚本中,我有 3 个变量:x、y、z。

I have a thread running alongside the curses loop that increments x, y, and z every x seconds.我有一个线程与curses 循环一起运行,它每x 秒递增x、y 和z。 In the loop I am simply printing the three variables to the terminal screen.在循环中,我只是将三个变量打印到终端屏幕。

The problem : The variables do not update until I provide some kind of input.问题:在我提供某种输入之前,变量不会更新。 How can I make the terminal string update the values automagically?如何让终端字符串自动更新值?

I am testing this on a Terminal on Kubuntu.我正在 Kubuntu 上的终端上对此进行测试。 I tried Urwid and ran into a similar problem.我尝试了 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)

Expected : The values of x, y, and z are displayed and reflect the increments without input.预期:显示 x、y 和 z 的值,并在没有输入的情况下反映增量。

Actual results : The values of x, y, and z remain 1, 2, and 3 respectively and updates only when I press a key.实际结果:x、y 和 z 的值分别保持为 1、2 和 3,并且仅在我按下某个键时更新。

----------- Edit: This works as expected: -----------编辑:这按预期工作:

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)

But I will need the values to be updated from a thread.但是我需要从线程更新值。

The issue was that c = screen.getch() was blocking the loop and preventing the values from being updated.问题是c = screen.getch()阻塞了循环并阻止更新值。

Removing...正在删除...

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

... produced the intended results. ...产生了预期的结果。

Thank you NEGR KITAEC谢谢 NEGR KITAEC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM