如何使线程更新的字符串反映 Python 的诅咒变化?
How can I made a string that is updated by a thread reflect the changes on Python's curses?
我正计划将 curses 库实施到客户端的现有 Python 脚本中。该脚本将 运行 完全通过 SSH。
我目前正在尝试模拟我的脚本将生成的一些输出。
在我的 'testing-the-waters' 脚本中,我有 3 个变量:x、y、z。
我在 curses 循环旁边有一个线程 运行ning,每 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)
但我需要从线程更新值。
问题是 c = screen.getch()
阻塞了循环并阻止了值的更新。
正在删除...
c = screen.getch()
if c == ord('q'):
go = False
...产生了预期的结果。
谢谢 NEGR KITAEC
我正计划将 curses 库实施到客户端的现有 Python 脚本中。该脚本将 运行 完全通过 SSH。
我目前正在尝试模拟我的脚本将生成的一些输出。
在我的 'testing-the-waters' 脚本中,我有 3 个变量:x、y、z。
我在 curses 循环旁边有一个线程 运行ning,每 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)
但我需要从线程更新值。
问题是 c = screen.getch()
阻塞了循环并阻止了值的更新。
正在删除...
c = screen.getch()
if c == ord('q'):
go = False
...产生了预期的结果。
谢谢 NEGR KITAEC