问题就在这里。在下面的代码中,我希望产生一个“移动光标”的效果。代码如下:
sys.stdout.write('\033[2K\033[1G')
time.sleep(2)
print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.viru|s.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print('virus_prevention.fix.vir|us.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.vi|rus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.v|irus.attempt.enter')
time.sleep(0.1)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix.|virus.attempt.enter')
time.sleep(2)
sys.stdout.write('\033[2K\033[1G')
print ('virus_prevention.fix|virus.attempt.enter')这是输出:
[2K[1Gvirus_prevention.fix.virus.|attempt_enter
[2K[1Gvirus_prevention.fix.virus|.attempt_enter
[2K[1Gvirus_prevention.fix.viru|s.attempt.enter
[2K[1Gvirus_prevention.fix.vir|us.attempt.enter
[2K[1Gvirus_prevention.fix.vi|rus.attempt.enter
[2K[1Gvirus_prevention.fix.v|irus.attempt.enter
[2K[1Gvirus_prevention.fix.|virus.attempt.enter而且sys.stdout.write也帮不上什么忙。它只是在当前文本的前面添加了文本。因此,如果有任何人愿意分享(Python 3)的解决方案,请尽管使用。(我确实有一个解决方案,通过os.system('clear')反复清除屏幕,但我并不真的想使用它。)
发布于 2020-05-29 22:52:07
sys.stdout.write是一个很好的开始,但是您还需要传递一个“回车”'\r'来跳转到行的开头。这将用下一次调用覆盖旧字符:
for i in range(10):
sys.stdout.write(str(i)+'\r')
time.sleep(1)如果新行比前一行短,您仍将看到前一行的附加字符。作为修复,您可以添加一些额外的空格来覆盖它们。
sys.stdout.write和print之间的主要区别是,print会自动附加一个换行符(\n)。这就是为什么您会看到下一个打印行前面的sys.stdout.write。
在交互式Python会话中运行它有一些奇怪的副作用,但是如果您在Python脚本中使用它就可以了。此外,请确保中间没有任何其他print()命令。这只适用于当前行,并且任何'\n'都会创建一个新行。
sys.stdout.write('virus_prevention.fix.virus.|attempt_enter\r')
time.sleep(2)
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter\r')
print() # create a linebreak at the end发布于 2020-05-29 23:00:01
这与您希望实现的目标类似,您需要调整它以适应您希望“光标”显示的位置
import time
displayText = "Python"
character = '|'
for i in range(len(displayText)+1):
print(displayText[:i] + character + displayText[i:], end='\r')
time.sleep(.2)
input()这将在通过控制台/命令提示符执行时提供所需的效果;但不是通过Python的空闲Shell执行。
https://stackoverflow.com/questions/62088666
复制相似问题