python - 由于意外的鼠标/键盘输入,tqdm 在 Windows 控制台上崩溃

标签 python windows tqdm

在 Windows 上运行任何使用 tqdm 进度条的应用程序已经变得非常令人头疼。

我不清楚这是否是 Windows 错误,但该错误很容易重现。在 cmd.exePowershell 上运行以下代码:

from tqdm import *
import time

counter = 1000
for i in tqdm(range(counter)):
     time.sleep(.01)

当进度条增加时,您可以执行以下操作来触发崩溃:

  • 使用鼠标左键在窗口中选择几个字符(即使是空格也可以,如下面的屏幕截图所示),然后右键单击或按任意键使应用程序崩溃:

enter image description here

错误消息显示:

Traceback (most recent call last):
  File "tqdmTest.py", line 5, in <module>
    for i in tqdm(range(counter)):
  File "C:\Users\brcod\AppData\Roaming\Python\Python34\site-packages\tqdm\_tqdm.py", line 979, in __iter__
    sp(self.__repr__())
  File "C:\Users\brcod\AppData\Roaming\Python\Python34\site-packages\tqdm\_tqdm.py", line 241, in print_status
    fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
  File "C:\Users\brcod\AppData\Roaming\Python\Python34\site-packages\tqdm\_tqdm.py", line 234, in fp_write
    fp.write(_unicode(s))
OSError: raw write() returned invalid length 306 (should have been between 0 and 153)

我在 Windows 10 上使用 Python 3.4.4tqdm 4.19.5

这非常烦人,因为当我试图单击鼠标来聚焦窗口时,鼠标意外选择了窗口中的几个字符。

谁能解释一下为什么会发生这种情况?这个问题有适当的解决方法吗?

最佳答案

解决方案 1:此问题最简单的解决方案是在 cmd.exe 窗口的属性中禁用快速编辑模式,以防止意外选择和粘贴文本导致的鼠标点击:

解决方案 2:这也可以通过编程方式处理。只需重写循环来捕获异常并在异常发生时传递它:

from tqdm import *
import time

maxCount = 1000
pbar = tqdm(total = maxCount)

for i in range(maxCount+1):
     try:
          pbar.update(i - pbar.n)
     except OSError as e:
          pass

     time.sleep(.01)

pbar.close()

关于python - 由于意外的鼠标/键盘输入,tqdm 在 Windows 控制台上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371993/

相关文章:

c++ - 在 Windows 上放弃权利

Python tqdm 和打印奇怪的打印输出顺序

python - 如何将文本文件中的这些数字加在一起?

python - 删除textarea标签中的%s python

c# - Windows defrag 不是内部或外部命令,也不是可运行的程序或批处理文件

python - 使用用户输入作为Python 3中保存文件的路径?

python - Jupyter Notebook 中的 tqdm 重复打印新的进度条

python - 在 tqdm 中的 for 循环后更改描述

python - 使用 str.split (panda) 拆分一列时强制列数

python - 如何在 python 中添加两个 OrderedDict 对象的值,保持顺序?