Не уверен, что я упускаю что-то очевидное, но вот что происходит: у меня есть скрипт на python 2.4.3, который содержит несколько объектов RegEx.Ниже один из объектов регулярных выражений ищет все совпадения в строке (tMatchList).Даже если tMatchList не равен NULL, он печатает пустой набор после шага «if p:».Это происходит даже в том случае, если оно печатается правильно до шага «if p:».Я думал, что это, возможно, проблема с областью действия, но все объявлено и содержится в одной функции.Я не совсем понимаю, как шаг 'if p:' не может увидеть tMatchList.Я также могу напечатать tMatchList после оператора if.
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
p = self._pdfPathRegex.search(lines)
print tMatchList #tMatchList is printing just fine here if it has any elements
if p:
print tMatchList #now it's empty,
#even if it printed elements in prior statement
lines = .....
else:
<something else gets done>
print tMatchList #now it prints again
Включая полное определение функции для тех, кто хотел бы ее увидеть ....
def FindFilesAndModifyPDFTag(self, inRootDirArg, inRollBackBool):
for root, dirs, files in os.walk(inRootDirArg):
for d in dirs:
if d.startswith('.'):#excludes directories that start with '.'
continue
for file in files:
if os.path.splitext(file)[1] == self._fileExt:
#Backup original. just do it
shutil.copy2(os.path.join(root, file), os.path.join(root, file)+"~")
r = open(os.path.join(root, file)+"~", "r")
f = open(os.path.join(root, file), "w")
linecount = 0
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
t = self._testReplacePDFTag.search(lines)
#find pdf path(s) in line
pMatchList = self._pdfPathRegex.findall(lines)
p = self._pdfPathRegex.search(lines)
#fix the pdf tracking code
print id(tMatchList), "BEFORE"
if p:
print id(tMatchList), "INSIDE"
lines = self.processPDFTagLine(pMatchList, lines, linecount, file, tMatchList)
else:
lines = self.processCheckMetaTag(lines, linecount, file)
#print id(tMatchList), "INSIDE ELSE"
print id(tMatchList), "AFTER"
f.writelines(lines)
f.close()
r.close()
os.remove(os.path.join(root, file)+"~")
enter code here