سؤال

I had a script parsing an html file which worked perfectly well until I changed it slightly, making it possible to run it from the terminal, like this:

python myscript.py filename

So, when indicating the direct name of the file to parsed, it works:

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

Then instead of the exact name of the file I indicated a variable which should be then used as an argument in the command line:

 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

Here is the error I get: Traceback (most recent call last):

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
هل كانت مفيدة؟

المحلول

filename = sys.argv[0]

There's your problem. I suspect you meant to do:

filename = args[0]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top