使用python并行打印多个滚动线

时间:2013-07-23 12:26:28

标签: python parallel-processing

尝试使用python在终端上打印多个滚动线。以下是代码:

import os, sys, time
import threading

def scroll_text(content, line, scroll_limit, sleep_time):
    blank_line = "\r" + " " * scroll_limit
    buf = ""

    if line > 0:
        sys.stdout.write("\r\n" * line)
        sys.stdout.flush()
    for cindex in range(0, len(content), 1):
        sys.stdout.write(blank_line)
        sys.stdout.flush()
        buf = content[cindex:cindex + scroll_limit]
        for itr in range(0, len(buf), 1):
            if buf[itr] == "\n":
                buf[itr] = "-"
        buf = "".join(buf)
        if buf != "":
            sys.stdout.write("\r" + buf)
            sys.stdout.flush()

        time.sleep(sleep_time)

fd = open('chat.txt', 'r')
content = fd.read()

content_list = list(content)

fd.close()

thread1 = threading.Thread(target=scroll_text, args=(content_list, 0, 70, 0.05))
thread2 = threading.Thread(target=scroll_text, args=(content_list, 1, 70, 0.05))
thread1.start()
thread2.start()
thread1.join()
thread2.join()

注意到只调用了第二个线程,并且文本在第二行上滚动。不知道我在这里做错了什么。我是新手,所以请原谅我的编码错误

添加了:

以下是curses版本:

import os, sys, time
import threading
import curses

def report(line_no, text):
        stdscr.addstr(line_no, 0, text)
        stdscr.refresh()

def scroll_text(content, line, scroll_limit, sleep_time):
    itr1 = 0
    for itr in range(0, len(content) - 1, 1):
        if content[itr] == "\n" or content[itr] == "\r\n":
            content[itr] = '-'

    report(line, "\r" + " " * scroll_limit + "\r")
    for itr in range(0, len(content), 1):
        buf = "".join(content[itr:itr + scroll_limit])

        buf = buf.rstrip()

        if buf != "":
            report(line, "\r" + buf)
        time.sleep(sleep_time)

fd = open('chat.txt', 'r')
content = list(fd.read())
fd.close()

stdscr = curses.initscr()
curses.noecho()
curses.cbreak()

try:
    thread1 = threading.Thread(target=scroll_text, args=(content, 0, 70, 0.05))
    thread2 = threading.Thread(target=scroll_text, args=(content, 1, 70, 0.05))
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

except:
    curses.echo()
    curses.nocbreak()
    curses.endwin()
finally:
    curses.echo()
    curses.nocbreak()
    curses.endwin()

以下是带有curses版本

的输出的video

1 个答案:

答案 0 :(得分:0)

一些简单的评论:

  • 我不明白为什么你将content_list复制为content1content2以便稍后将content1作为参数传递两次。也许你的第二个帖子应该使用content2而不是content1

    thread2 = threading.Thread(target=scroll_text, args=(content2, 1, 70, 0.05))
    
  • 您应该在结尾处关闭文件句柄,例如:

    fd.close()
    
  • 您可能故意使用sys.stdout.write(),我只想提及以下打印到STDOUT的方式:

    from __future__ import print_function   # python3 compatible, changes the syntax a little bit
    
    print (something)   # newline is inclusive, you don't need to add '+ \n'