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

7 python linux multithreading ncurses

我的脚本中有两个工作。一旦作业开始,其他作业将异步运行。我为此使用了线程。这个线程会返回一些信息,而其他线程会计算这些信息。

我想要做的是在计数器的值发生变化的同时,线程也继续运行。

我想要的显示:

-----------------------------------------
Count: 5
-----------------------------------------
thread keeps running...
thread keeps running...
thread keeps running...
Run Code Online (Sandbox Code Playgroud)

实际上我使用curses模块实现了这个目标,但这并不是我想要的。因为当我按下^C终端内容时。我希望它们冻结在屏幕上。

带有诅咒的代码:

-----------------------------------------
Count: 5
-----------------------------------------
thread keeps running...
thread keeps running...
thread keeps running...
Run Code Online (Sandbox Code Playgroud)

有没有办法在不使用curses或不丢失内容的curses的情况下实现相同的目标?

谢谢!

Anm*_*ggi 5

尝试这个:

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

Run Code Online (Sandbox Code Playgroud)