为什么 clear_output() 不清除在 VS 代码中打印到 python 控制台的内容?
Why doesn't clear_output() clear what's printed to the python console in VS code?
编程新手,目前正在研究网络抓取工具。当我使用 IPython.display 中的 clear_output() 时,我试图监控我的进度并保持我的终端清洁,但它似乎没有清除我在 VSCode 中的输出。这是一个例子:
from time import sleep
from IPython.display import clear_output
x = 0
while x < 5:
x += 1
sleep(.2)
print(x)
clear_output(wait=True)
我希望它清除 x 的先前值以代替新值,但它没有。程序完成后,我的输出将从:
>>>1
>>>2
>>>3
>>>4
>>>5
to:
>>>1
>>>2[2K
>>>3[2K
>>>4[2K
>>>5[2K
猜测这是来自 IPython 的内容,但我不确定它的含义或如何修复它。感谢您的帮助!
我不确定这是否是您要问的,但您可以尝试使用 sys 库:
from time import sleep
from sys import stdout
for i in range(0, 1000):
stdout.write("\b") # \b for backspace, you may need \r depends on system
sleep(.9)
stdout.write("\b\b\b>>>" + str(i))
stdout.flush()
对我来说输出是:
>>>1
然后 1 被 2 替换
>>>2
2 替换为 3 等等
我睡了一觉,所以你可以看看会发生什么,如评论中所述,你可能需要将 \b 更改为 \r 或两者的某种组合
clear_output() 仅适用于 Jupyter。考虑使用 print('\n'100) 清除其他 IDE 中的输出。
编程新手,目前正在研究网络抓取工具。当我使用 IPython.display 中的 clear_output() 时,我试图监控我的进度并保持我的终端清洁,但它似乎没有清除我在 VSCode 中的输出。这是一个例子:
from time import sleep
from IPython.display import clear_output
x = 0
while x < 5:
x += 1
sleep(.2)
print(x)
clear_output(wait=True)
我希望它清除 x 的先前值以代替新值,但它没有。程序完成后,我的输出将从:
>>>1
>>>2
>>>3
>>>4
>>>5
to:
>>>1
>>>2[2K
>>>3[2K
>>>4[2K
>>>5[2K
猜测这是来自 IPython 的内容,但我不确定它的含义或如何修复它。感谢您的帮助!
我不确定这是否是您要问的,但您可以尝试使用 sys 库:
from time import sleep
from sys import stdout
for i in range(0, 1000):
stdout.write("\b") # \b for backspace, you may need \r depends on system
sleep(.9)
stdout.write("\b\b\b>>>" + str(i))
stdout.flush()
对我来说输出是:
>>>1
然后 1 被 2 替换
>>>2
2 替换为 3 等等
我睡了一觉,所以你可以看看会发生什么,如评论中所述,你可能需要将 \b 更改为 \r 或两者的某种组合
clear_output() 仅适用于 Jupyter。考虑使用 print('\n'100) 清除其他 IDE 中的输出。