Threading with Python Curses giving me weird characters?

旧城冷巷雨未停 提交于 2019-12-13 07:25:50

问题


Hey there Stack Overflow. I'm trying to build a testing script that should mix outputting changing characters (using curses) on multiple lines (creating them over time), creating new lines based on the thread number. I have the below code:

# -*- coding: utf-8 -*-
import curses, time, threading

def threadedFunction(linePos):
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        stdscr.clear()
        for i in range(50):
            stdscr.addstr(linePos, 0, "testing %s..." % i)
            stdscr.refresh()
            time.sleep(.1)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()
        pass
    pass

if __name__ == "__main__":
    for x in xrange(0, 4): # should produce 5 lines maximum
        exec("process" + str(x) + " = threading.Thread(target = threadedFunction, args = (" + str(x) + ",))")
        exec("process" + str(x) + ".start()")

I tried using the multithreading library before, but I had no hope with it. The threading library at least will display the numbers I want on a few lines before it goes crazy. Here's an example of what it does when I run it:

All I want is for the program to just simply start a new thread, and display a line that counts to 50 while adding new lines doing the same thing. How would I go about doing this?? Thanks in advance :)


回答1:


Printing to the terminal from multiple threads will give you intermingled output like that. It is a very simple example of race condition. Use some kind of locking mechanism to coordinate writes to the terminal, or make sure to only write from one thread (for example, using a FIFO to pass message to the writing thread, which will write them to the terminal).

The weird numbers you see are part of the ANSI escape sequences that are used by programs to use special features of the terminal: writing \x1B[nF to the output will make your terminal move the cursor one line up, for example. Curses is outputting such codes for you, and because the terminal interprets them according to the ANSI meaning, you don't usually see them. But because of the multithreading issue, those become mingled and invalid, and part of them get printed to the screen.




回答2:


Even if you only use curses in one thread, other processing-heavy threads can disrupt the escape sequences in the curses thread. The environment variable $ESCDELAY indicates how long (in ms) to wait after an escape code (0x1B) is sent; and if more than that time elapsed, a ^[ keystroke (ESC) is returned by get_wch().



来源:https://stackoverflow.com/questions/46773577/threading-with-python-curses-giving-me-weird-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!