问题
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