0

每当有对 的函数调用时,我都会不断收到以下错误xml(productline),但是如果我将函数调用替换为file = open('config\\' + productLine + '.xml','r'),它似乎可以工作,为什么?

def xml(productLine):
         with open('config\\' + productLine + '.xml','r') as f:
    return f.read()


def getsanityresults(productline):

xmlfile=xml(productline) // replace with file = open('config\\' + productLine + '.xml','r')
dom = minidom.parse(xmlfile)
data=dom.getElementsByTagName('Sanity_Results')
#print "DATA"
#print data
textnode = data[0].childNodes[0]
testresults=textnode.data
#print testresults
for line in testresults.splitlines():
    #print line
    line = line.strip('\r,\n')
    #print line
    line = re.sub(r'(http://[^\s]+|//[^\s]+|\\\\[^\s]+)', r'<a href="\1">\1</a>', line)
    print line
    #print line       
    resultslis.append(line)
print resultslis
return resultslis

错误:

Traceback (most recent call last):
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 910, in <module>
  main()
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 858, in main
testresults=getsanityresults(pL)
 File "C:\Dropbox\scripts\announce_build_wcn\wcnbuild_release.py", line 733, in   getsanityresults
  dom = minidom.parse(xmlfile)
File "C:\python2.7.3\lib\xml\dom\minidom.py", line 1920, in parse
   return expatbuilder.parse(file)
File "C:\python2.7.3\lib\xml\dom\expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 2] No such file or directory: '<root>\n    <PL name = "MSM8930.LA.2.0-PMIC-8917">\n
4

2 回答 2

1

我用 替换了函数调用file = open('config\\' + productLine + '.xml','r'),它似乎有效,为什么?

您有两个变量,名称略有不同:

xmlfile=xml(productline) // replace with file = open('config\\' + productLine + '.xml','r')

productline(小写l)和productLine(大写L)。

如果您在两种情况下都使用相同的变量,您可能会看到更一致的结果。

于 2012-11-20T21:41:56.080 回答
1

minidom.parse()期望文件名或文件对象作为参数,但您正在传递文件的内容,试试这个:

import os
from xml.dom import minidom

doc = minidom.parse(os.path.join('config', productline + '.xml'))

除非您有特定的要求minidom;用于xml.etree.cElementTree在 Python 中使用 xml。它更 Pythonic,lxml在更复杂的情况下您可能需要支持它的 API,因此您无需学习两次。

于 2012-11-20T22:50:45.553 回答