【发布时间】: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和内存在变化,但等待很长时间后没有任何反应。