【问题标题】:How to fix the '\r' function Windows/Mac OS [duplicate]如何修复 '\r' 功能 Windows/Mac OS [重复]
【发布时间】:2020-09-17 21:10:24
【问题描述】:

我有一个问题,我想删除一些打印,但它被完全忽略了,并且打印了几行。对于这些解决方案,我一直使用\r。有没有办法绕过这种情况? (我现在使用的是 Mac OS,但保证很快就会切换到 Windows。)@Feodoran 告诉我,\r 仅适用于 Linux 计算机,这是一个问题。代码如下:

print ('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
  sys.stdout.write(str(i)+'\r')
print ('virus_prevention.fix.virus|.attempt_enter')
time.sleep(0.1)
for i in range(1):
sys.stdout.write(str(i)+'\r')

输出如下:

virus_prevention.fix.virus.|attempt_enter
0
virus_prevention.fix.virus|.attempt_enter
0

我尝试过sys.stdout.write 而不是print,但似乎没有任何改变。我不确定在这种情况下该怎么做,但如果有人能给我一些建议,请做。它正在删除完全不起作用的打印行。

【问题讨论】:

  • 你想达到什么目的? for i in range(1): 只迭代一次,与它根本不存在是一样的。你在哪个终端调用你的 python 脚本(即它的显示方式取决于正在使用的终端和在哪个操作系统下(OS X 使用 \r 进行换行)
  • 其实你是对的。但是我现在还不清楚如何删除打印。
  • 这能回答你的问题吗? Terminal - How to overwrite many lines?MacOS 有解决方案,或许有帮助。
  • 不完全。它只是出现一个空白屏幕。第二个可能有效。
  • 不,语法无效。

标签: python python-3.x


【解决方案1】:
import time
import sys
sys.stdout.write('virus_prevention.fix.virus.|attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))
sys.stdout.write('virus_prevention.fix.virus|.attempt_enter')
time.sleep(2)
for i in range(1):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(str(i))

这能解决您的问题吗?

【讨论】:

  • 很遗憾,没有。
  • 你的问题能不能说得更具体一些,有一些歧义
  • 实际上,您的解决方案可能适用于 Windows 10。
  • 嗯,这是输出。 virus_prevention.fix.virus.|attempt_enter 0virus_prevention.fix.virus|.attempt_enter 0
  • 我在我的Linux机器上试了一下,结果刷新了,抱歉
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2019-09-15
  • 2015-07-26
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 2011-12-20
相关资源
最近更新 更多