问题出在这里。在下面的代码中,我希望产生一种“移动光标”的效果。代码如下:
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')
反复清除屏幕,我真的不想使用它。)
sys.stdout.write
是一个好的开始,但是您还需要传递一个“回车”'\r'
以跳到行的开头。这将在下次调用时覆盖旧字符:如果新行比前一行短,您仍将看到前一行的附加字符。作为修复,您可以添加一些额外的空格来覆盖它们
sys.stdout.write
和print
之间的主要区别在于print
将自动附加换行符(\n
)。这就是为什么您会看到下一行前面的sys.stdout.write
在交互式Python会话中运行它会产生一些奇怪的副作用,但是如果在Python脚本中使用它,这是很好的。另外,确保中间没有任何其他
print()
命令。这只适用于当前的行,任何'\n'
都会创建一个新行这与您希望实现的类似,您需要对其进行调整,以适应您希望“光标”显示的位置
这将在通过控制台/命令提示符执行时提供所需的效果;但不是通过Python的空闲外壳
相关问题 更多 >
编程相关推荐