gpt4 book ai didi

python - 如何在不使用线程作业更改其位置的情况下更新字符串的值? [Python]

转载 作者:行者123 更新时间:2023-12-02 09:37:30 25 4
gpt4 key购买 nike

我的脚本中有两个工作。一旦作业开始,其他作业将异步运行。我为此使用了线程。这个线程将返回一些信息,而其他计算该信息。
我想做的是在计数器的值发生变化的同时,线程也将继续运行。
显示我想要的:

-----------------------------------------
Count: 5
-----------------------------------------
thread keeps running...
thread keeps running...
thread keeps running...
实际上我使用 curses 来实现这个目标模块,但这并不是我想要的。因为当我按 ^C终端内容不见了。我希望他们在屏幕上卡住。
带有诅咒的代码:
import sys
import time
import queue
import signal
import curses
import threading


def ctrl_c_handler(*args):
sys.exit(0)


signal.signal(signal.SIGINT, ctrl_c_handler)

MESSAGE = "thread keeps running..."


def print_func(message):
return message


def new_window(stdscr):
que = queue.Queue()

curses.curs_set(False)

y, x = stdscr.getmaxyx()

draw = x * "-"

i = 3
count = 1
while True:
thread = threading.Thread(target=lambda q, arg1: q.put(print_func(arg1)), args=(que, MESSAGE,), daemon=True)
thread.start()
result = que.get()

try:
stdscr.addstr(0, 0, draw)
stdscr.addstr(1, 0, f"Count: {str(count)}")
stdscr.addstr(2, 0, draw)
stdscr.addstr(i, 0, result)

except curses.error:
pass

stdscr.refresh()
time.sleep(0.1)

i += 1
count += 1

if i == y:
stdscr.clear()
i = 3


curses.wrapper(new_window)

有没有办法在不使用诅咒的情况下实现相同的目标,或者在不丢失内容的情况下使用诅咒?
谢谢!

最佳答案

试试这个:

import sys
import time
import queue
import signal
import curses
import threading


ctrl_c_pressed_event = threading.Event()

def ctrl_c_handler(*args):
ctrl_c_pressed_event.set()


signal.signal(signal.SIGINT, ctrl_c_handler)

MESSAGE = "thread keeps running..."


def print_func(message):
return message


def new_window(stdscr):
que = queue.Queue()

curses.curs_set(False)

y, x = stdscr.getmaxyx()

draw = x * "-"

i = 3
count = 1
while True:
if ctrl_c_pressed_event.isSet():
stdscr.getkey()
break
thread = threading.Thread(target=lambda q, arg1: q.put(print_func(arg1)), args=(que, MESSAGE,), daemon=True)
thread.start()
result = que.get()
try:
stdscr.addstr(0, 0, draw)
stdscr.addstr(1, 0, f"Count: {str(count)}")
stdscr.addstr(2, 0, draw)
stdscr.addstr(i, 0, result)
except curses.error:
pass
stdscr.refresh()
time.sleep(0.1)
i += 1
count += 1
if i == y:
stdscr.clear()
i = 3


curses.wrapper(new_window)
print('Program ended')

关于python - 如何在不使用线程作业更改其位置的情况下更新字符串的值? [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63257319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com