使用python并行打印多个滚动行
正在尝试使用python在终端上打印多个滚动行。代码如下:使用python并行打印多个滚动行,python,parallel-processing,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)
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版本的输出的示例和一些简单的注释:
- 我不明白为什么要将
复制为content\u列表
和content1
,以便以后将content2
作为参数传递两次。也许您的第二个线程应该使用content1
,而不是content2
:content1
thread2 = threading.Thread(target=scroll_text, args=(content2, 1, 70, 0.05))
- 最后应关闭文件句柄,例如:
fd.close()
- 您可能有意使用了
,我只想提到以下打印到stdout的方法:sys.stdout.write()
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'