问题描述
我想展示这个系列进行实验。
A
B
AA
BB
AAA
BBB
不添加新行,就像仅对'A'起作用一样。 这仅是A的代码,并且可以使用。
root@kali-linux:/tmp# cat a.py
import time
x = "A"
while True:
print(x,end = "\r")
x += "A"
time.sleep(1)
现在我加了B。
root@kali-linux:/tmp# cat a.py
import time
x = "A"
y = "B"
while True:
print(x,end = "\r")
print(y,end = "\r")
x += "A"
y += "B"
time.sleep(1)
不幸的是,B吃掉了A,只有B增加了。我试过这样的东西,但它会引起我不想要的重复
import time
x = "A"
y = "B"
while True:
print(x,end = "\r")
print('\n',end='\r')
print(y,end = "\r")
x += "A"
y += "B"
time.sleep(1)
有没有办法重复印刷系列?我得到了这个答案,但似乎很难在python3中实现。
\r moves back to the beginning of the line,it doesn't move to a new line (for that you need \n). When you have 'A' and 'B' it writes all the 'A's and then overwrites it with the 'B's.
You would need to loop through all the 'A's,then print a new line \n,then loop for the 'B's.
编辑
诅咒和色瘤的回答都可以,但是除了尝试之外,诅咒会导致终端死亡,并且它有些不可改变。但是科罗拉多很容易。另外,由于不需要120
新行,因此应稍作修改。
os.sytem('clear')
之后执行 colorama.init()
。科罗拉多州答案的主要部分是这个print("\x1b[%d;%dH" % (1,1),end="")
。
也结帐App using this question answer
解决方法
就使用\ r和\ n而言,我不确定是否遇到了执行此操作的方法。我通常用于自定义CLI输出的是模块 colorama 。使用一些控制位,您可以将文本放置在屏幕上所需的任何位置,甚至可以使用不同的颜色和样式。
网站:https://pypi.org/project/colorama/
代码:
# Imports
import time
import colorama
# Colorama Initialization (required)
colorama.init()
x = "A"
y = "B"
# Clear the screen for text output to be displayed neatly
clearLine = "\n"
for _ in range(120):
clearLine += "\n"
print("\x1b[%d;%dH%s" % (1,1,clearLine))
while True:
# Position the cursor back to the 1,1 coordinate
print("\x1b[%d;%dH" % (1,1),end="")
# Continue printing
print(x)
print(y)
x += "A"
y += "B"
time.sleep(1)
,
curses
module在这里很有用。
快速演示:
import time
import curses
win = curses.initscr()
for i in range(10):
time.sleep(0.5)
win.addstr(0,"A" * i)
win.addstr(1,"B" * i)
win.refresh()
curses.endwin()
curses.initscr()
创建一个覆盖整个终端的“窗口”。 It doesn't have to,though
addstr(y,x,string)
将字符串添加到给定位置。
您可以找到许多有关如何摆弄curses
的信息,以使其完全按照文档中的要求进行操作