npyscreen输出消息逐层缩进错位的解决方法
npyscreen脚本print输出缩进错位问题解决
问题现象
基于npyscreen编写的Python脚本,先通过npyscreen表单采集用户输入,后续执行过程中直接用print输出进度提示时,会出现逐层向右缩进的错位问题,异常显示效果如下:
Something Something Something
问题复现代码
import npyscreen, time class Test(npyscreen.NPSApp): def main(self): F = npyscreen.Form(name = "Test") color = F.add(npyscreen.TitleText, name = "Color:") F.edit() if(color.value == "Something"): self.call_function_to_display_messages(color.value) def call_function_to_display_messages(self, color): print(color) print(color) print(color) time.sleep(10) if __name__ == "__main__": App = Test() App.run()
问题原因
npyscreen底层基于curses库实现终端UI控制,表单编辑退出后不会自动完全重置终端的光标状态,此时直接调用原生print输出时,光标不会自动回到行首,每次输出都会从上次光标停留的列位置开始打印,最终形成逐层缩进的错位效果。
解决方法
根据使用场景二选一即可:
- 后续不需要回到npyscreen界面,直接在终端输出文本
在执行print输出前,显式调用curses的endwin方法重置终端到默认状态,即可恢复正常的print输出行为。修改后的核心代码如下:import npyscreen, time import curses # 新增导入curses库 class Test(npyscreen.NPSApp): def main(self): F = npyscreen.Form(name = "Test") color = F.add(npyscreen.TitleText, name = "Color:") F.edit() if(color.value == "Something"): self.call_function_to_display_messages(color.value) def call_function_to_display_messages(self, color): curses.endwin() # 新增该行重置终端状态 print(color) print(color) print(color) time.sleep(10) if __name__ == "__main__": App = Test() App.run() - 后续还需要保留npyscreen界面交互
不要直接使用原生print输出,改用npyscreen内置的组件输出消息:- 临时提示可以用
npyscreen.notify()、npyscreen.notify_wait()这类内置通知方法 - 持续更新的进度日志,可以在表单中添加
MultiLine控件,把进度消息追加到控件的values列表中,再调用display方法刷新界面即可,这类输出会自动适配npyscreen排版规则,不会出现错位。
- 临时提示可以用
注意:不要在npyscreen表单的活动周期内直接调用原生print输出内容,所有界面内的输出都应该通过npyscreen提供的组件API实现,否则大概率会出现格式错乱、光标异常的问题。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

