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

2024-06-03 04:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的脚本中,我将有两份工作。一旦作业启动,其他作业将异步运行。我用线做这个。这个线程将返回一些信息,而其他线程将计算这些信息

我想做的是,当计数器的值改变时,线程也会继续运行

显示我想要的:

-----------------------------------------
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)

有没有一种方法可以实现同样的目标而不使用诅咒,或者诅咒内容不会丢失

谢谢大家!


Tags: import信息signaldefcount作业线程thread
2条回答

试试这个:

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')

curses.wrapper就是这样做的。按如下方式更改ctrl_c_handler函数:

def ctrl_c_handler(*args):
    curses.nocbreak()
    scr.keypad(False)
    curses.echo()
    sys.exit(0)

并不像使用wrapper函数那样启动new_window

scr = curses.initscr()
new_window(scr)

相关问题 更多 >