我有一个解析html文件的脚本,该文件运行得非常好,直到我稍微更改它,从而可以从终端运行它,如下所示:
python myscript.py filename
因此,当指出要解析的文件的直接名称时,它可以工作:
tree = etree.parse("folder/filename.html")
places = []
def f1():
for dfn in tree.getiterator('dfn'):
...
return places
def main():
f1()
file_places = open('list_places.txt', 'w')
for x in sorted(places):
print>>file_places, x
然后我指示一个变量,而不是文件的确切名称,然后在命令行中将其用作参数:
args=sys.argv[1:]
filename = sys.argv[0]
tree = etree.parse(filename)
places = []
def extract_places():
for dfn in tree.getiterator('dfn'):
...
return places
def main():
if len(args) < 1:
print 'usage: extract.py [file ...]'
sys.exit(1)
else:
extract_places()
file_places = open('list_places.txt', 'w')
for x in sorted(places):
print>>file_places, x
这是我得到的错误: 回溯(最近一次调用最后一次):
File "extract.py", line 15, in <module>
tree = etree.parse(filename)
File "lxml.etree.pyx", line 2957, in lxml.etree.parse (src/lxml/lxml.etree.c:56299)
File "parser.pxi", line 1533, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:82382)
File "parser.pxi", line 1562, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:82675)
File "parser.pxi", line 1462, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:81714)
File "parser.pxi", line 1002, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:78623)
File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74567)
File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75458)
File "parser.pxi", line 590, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74791)
lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1
答案 0 :(得分:4)
filename = sys.argv[0]
有你的问题。我怀疑你打算这样做:
filename = args[0]