【问题标题】:Python Loop Count Stops at 67381Python 循环计数在 67381 处停止
【发布时间】:2017-10-12 19:20:15
【问题描述】:

我假设这一定是内存问题,但我不确定。该程序通过 PDF 循环查找损坏的文件。当文件损坏时,它会将该位置写入 txt 文件供我稍后查看。第一次运行它时,我将通过和失败的情况都记录到日志中。在 67381 个日志条目之后,它停止了。然后我改变了这个逻辑,所以它只记录错误,但是,在控制台中我确实显示了循环的计数,所以我可以知道这个过程有多远。大约有 190k 文件要循环,并且每次都在 67381 处停止计数。看起来python程序仍在后台运行,因为内存和cpu一直在波动,但很难确定。我现在也不知道它是否还会将错误写入日志。

这是代码,

import PyPDF2, os
from time import gmtime,strftime

path = raw_input("Enter folder path of PDF files:")
t = open(r'c:\pdf_check\log.txt','w')
count = 1
for dirpath,dnames,fnames in os.walk(path):
    for file in fnames:
        print count
        count = count + 1
        if file.endswith(".pdf"):
            file = os.path.join(dirpath, file)
            try:
                PyPDF2.PdfFileReader(open(file, "rb"))
            except PyPDF2.utils.PdfReadError:
                curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
                t.write (str(curdate) + " " + "-" + " " + file + " " + "-" + " " + "fail" + "\n")
            else:
                pass
                #curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
                #t.write(str(curdate) + " " + "-" + " " + file + " " + "-" + " " + "pass" + "\n")

t.close()

编辑 1:(新代码) 新代码和同样的问题:

import PyPDF2, os
from time import gmtime,strftime

path = raw_input("Enter folder path of PDF files:")
t = open(r'c:\pdf_check\log.txt','w')
count = 1
for dirpath,dnames,fnames in os.walk(path):
    for file in fnames:
        print count
        count = count + 1
        if file.endswith(".pdf"):
            file = os.path.join(dirpath, file)
            try:
                with open(file,'rb') as f:
                    PyPDF2.PdfFileReader(f)
            except PyPDF2.utils.PdfReadError:
                curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
                t.write (str(curdate) + " " + "-" + " " + file + " " + "-" + " " + "fail" + "\n")
                f.close()
            else:
                pass
                f.close()
                #curdate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
                #t.write(str(curdate) + " " + "-" + " " + file + " " + "-" + " " + "pass" + "\n")

t.close()

编辑 2:我现在正尝试从具有更强大硬件和不同版本 Windows(10 pro 而不是 server 2008 r2)的不同机器上运行它,但我认为这不是问题。

【问题讨论】:

  • PyPDF2.PdfFileReader(open(file, "rb")) 不能保证关闭文件。使用上下文管理器使文件句柄关闭(不会受到伤害)
  • 它是如何停止的?默默地?
  • 是的,它只是冻结了,python程序仍在任务管理器中运行,cpu和内存在变化,但等待很长时间后没有任何反应。

标签: python pdf


【解决方案1】:

尝试编辑其中一个 .pdf 文件以使其更大。这样,如果您的程序“停止”的循环数较小,您可以将问题识别为内存问题。

否则,它可能是一个异常的大型 pdf 文件,它需要您的程序一段时间来验证完整性。

对此进行调试,您可以打印您打开的 .pdf 文件的文件位置以查找此特定 .pdf 并手动打开它以进一步调查..

【讨论】:

    【解决方案2】:

    想通了。该问题实际上是由于随机且非常大的损坏的 PDF 造成的。所以这不是循环问题,而是文件损坏问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 2020-05-28
      • 2013-11-29
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      相关资源
      最近更新 更多