Python Multiple Line Terminal Update

≡放荡痞女 提交于 2019-12-25 03:19:17

问题


Short Question
Is it possible/practical to write and update a multi-line (contains \n) string on a Windows terminal?

Background
I have looked into curses, but it is Unix only. I saw a few other Window ports, but it was a bit troubling that Windows XP was an experimental OS for one them. I am hoping to use this as part of a diagnostic feature to display link status, message rates, etc on a mainly terminal application (note that some variants do have a wxPython GUI input). That being said, using Cygwin is non-ideal and would love to find a workaround using only the sys module.

I have tried the following: (note that I expected them to fail, but hoped I would be wrong)
Attempt 1: Updates the string but it is all on 1 line

sys.stdout.write("\r")
sys.stdout.write("This is a multi-line screen print test") 
sys.stdout.write("Line 1") 
sys.stdout.write("Line 2") 
sys.stdout.flush()  

Attempt 2: Does not update but prints all the lines

sys.stdout.write("\r")
sys.stdout.write("This is a multi-line screen print test\n") 
sys.stdout.write("Line 1 \n") 
sys.stdout.write("Line 2\n") 
sys.stdout.flush()

回答1:


The closest thing I could find to curses (that has been updated in the last 10 years) was Windows Console Driver. Rather than use this approach I went at it was a less elegant method.

import os
import time

while(1):
    time.sleep(.05)
    os.system('cls')
    print "This is a multi-line screen print test"
    print "Line 1" 
    print "Line 2" 



回答2:


You might have to use the Windows Console API. For example, SetConsoleCursorPosition. Other people appear to have implemented Python modules to support this API: 1, 2



来源:https://stackoverflow.com/questions/7122775/python-multiple-line-terminal-update

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