在 python curses 中换行输出
output on a new line in python curses
我在 python 中使用 curses 模块通过读取文件实时显示输出。
使用 addstr() 函数将字符串消息输出到控制台
但是我无法在任何需要的地方打印到换行符。
示例代码:
import json
import curses
w=curses.initscr()
try:
while True:
with open('/tmp/install-report.json') as json_data:
beta = json.load(json_data)
w.erase()
w.addstr("\nStatus Report for Install process\n=========\n\n")
for a1, b1 in beta.iteritems():
w.addstr("{0} : {1}\n".format(a1, b1))
w.refresh()
finally:
curses.endwin()
以上并不是每次迭代都将字符串真正输出到新行(注意 addstr() 中的 \n)。相反,如果我调整终端 window 的大小,脚本会因错误而失败。
w.addstr("{0} ==> {1}\n".format(a1, b1))
_curses.error: addstr() returned ERR
程序不足,只能提供一般建议:
- 如果您的脚本不启用滚动,则在打印到屏幕末尾时会出现错误(请参阅
window.scroll
)。
- 如果您调整终端 window 的大小,您将必须读取键盘以处理任何
KEY_RESIZE
(并忽略错误)。
关于扩展问题,这些功能将像这样使用:
import json
import curses
w=curses.initscr()
w.scrollok(1) # enable scrolling
w.timeout(1) # make 1-millisecond timeouts on `getch`
try:
while True:
with open('/tmp/install-report.json') as json_data:
beta = json.load(json_data)
w.erase()
w.addstr("\nStatus Report for Install process\n=========\n\n")
for a1, b1 in beta.iteritems():
w.addstr("{0} : {1}\n".format(a1, b1))
ignore = w.getch() # wait at most 1msec, then ignore it
finally:
curses.endwin()
我在 python 中使用 curses 模块通过读取文件实时显示输出。 使用 addstr() 函数将字符串消息输出到控制台 但是我无法在任何需要的地方打印到换行符。
示例代码:
import json
import curses
w=curses.initscr()
try:
while True:
with open('/tmp/install-report.json') as json_data:
beta = json.load(json_data)
w.erase()
w.addstr("\nStatus Report for Install process\n=========\n\n")
for a1, b1 in beta.iteritems():
w.addstr("{0} : {1}\n".format(a1, b1))
w.refresh()
finally:
curses.endwin()
以上并不是每次迭代都将字符串真正输出到新行(注意 addstr() 中的 \n)。相反,如果我调整终端 window 的大小,脚本会因错误而失败。
w.addstr("{0} ==> {1}\n".format(a1, b1))
_curses.error: addstr() returned ERR
程序不足,只能提供一般建议:
- 如果您的脚本不启用滚动,则在打印到屏幕末尾时会出现错误(请参阅
window.scroll
)。 - 如果您调整终端 window 的大小,您将必须读取键盘以处理任何
KEY_RESIZE
(并忽略错误)。
关于扩展问题,这些功能将像这样使用:
import json
import curses
w=curses.initscr()
w.scrollok(1) # enable scrolling
w.timeout(1) # make 1-millisecond timeouts on `getch`
try:
while True:
with open('/tmp/install-report.json') as json_data:
beta = json.load(json_data)
w.erase()
w.addstr("\nStatus Report for Install process\n=========\n\n")
for a1, b1 in beta.iteritems():
w.addstr("{0} : {1}\n".format(a1, b1))
ignore = w.getch() # wait at most 1msec, then ignore it
finally:
curses.endwin()