首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何删除打印

如何删除打印
EN

Stack Overflow用户
提问于 2020-05-29 22:48:34
回答 2查看 103关注 0票数 0

问题就在这里。在下面的代码中,我希望产生一个“移动光标”的效果。代码如下:

代码语言:javascript
复制
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')

这是输出:

代码语言:javascript
复制
[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')反复清除屏幕,但我并不真的想使用它。)

EN

回答 2

Stack Overflow用户

发布于 2020-05-29 22:52:07

sys.stdout.write是一个很好的开始,但是您还需要传递一个“回车”'\r'来跳转到行的开头。这将用下一次调用覆盖旧字符:

代码语言:javascript
复制
for i in range(10):
    sys.stdout.write(str(i)+'\r')
    time.sleep(1)

如果新行比前一行短,您仍将看到前一行的附加字符。作为修复,您可以添加一些额外的空格来覆盖它们。

sys.stdout.writeprint之间的主要区别是,print会自动附加一个换行符(\n)。这就是为什么您会看到下一个打印行前面的sys.stdout.write

在交互式Python会话中运行它有一些奇怪的副作用,但是如果您在Python脚本中使用它就可以了。此外,请确保中间没有任何其他print()命令。这只适用于当前行,并且任何'\n'都会创建一个新行。

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2020-05-29 23:00:01

这与您希望实现的目标类似,您需要调整它以适应您希望“光标”显示的位置

代码语言:javascript
复制
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执行。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62088666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档