Python: использование файла argparse, Pass, read и change html в классе, а также со словарем прохода и списком с использованием argparse через CL - PullRequest
0 голосов
/ 25 апреля 2020

Я пытаюсь передать файл, прочитать его и изменить его содержимое с помощью argparse. Я передаю несколько словарей и список. Это не работает. Вот ошибка, которую я получаю:

$ python practice.py templateP.html '{"title":"TEST"}' ITEM1 ITEM2 ITEM2
Traceback (most recent call last):
  File "practice.py", line 33, in <module>
    one = Core(args)
  File "practice.py", line 14, in __init__
    self.title = args.title
AttributeError: 'Namespace' object has no attribute 'title'

Например, словарь и списки:

 title1 = {'title':'TEST'}
ouritems = ['ITEM1','ITEM2','ITEM3']

Это содержимое файла html: названо как templateP. html

<html> 

<meta> 

    <title tal:content="context.title" /> 

    <body  > 

        <div tal:condition="items"> 

             <p>These are your items:</p> 

             <ul> 

                  <li tal:repeat="item items" tal:content="item" /> 

             </ul>             

        </div> 

     </body> 

</html>

Это код:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import argparse
    import os.path
    from chameleon import PageTemplateLoader
    from chameleon import PageTemplate
    import json

    class Core:

    def __init__(self,args):
        self.templatestr = args.Sfile
        self.title = args.title
        self.item = args.ouritems

    def __call__(self,args):
        self.pagetemplate =  PageTemplate(args.Sfile)
        return self.pagetemplate.render(context = args.title, item = args.ouritems )



parser = argparse.ArgumentParser(description='template to html book cover')
parser.add_argument( 'Sfile', help="input html template file", type=argparse.FileType('r'))
parser.add_argument('Title', help='Dictionary:Title of the book cover', type=json.loads )
parser.add_argument('ouritems', help='list of items at the back cover', nargs='+')
args = parser.parse_args()
templatestr = args.Sfile.readlines()
one = Core(args)
newTemplate = one.__call__(args)
print(newTemplate)

Если у кого-то есть идеи, что здесь не так и как это работает, я буду очень признателен.

Это новая ошибка, которую я получаю после добавления печати (аргументы) и изменения названия.

$ python practice.py templateP.html '{"title":"TEST"}' [ITEM1 ITEM2 ITEM2]
Namespace(Sfile=<_io.TextIOWrapper name='templateP.html' mode='r' encoding='UTF-8'>, Title={'title': 'TEST'}, ouritems=['[ITEM1', 'ITEM2', 'ITEM2]'])
Traceback (most recent call last):
  File "practice.py", line 31, in <module>
    newTemplate = one.__call__(args)
  File "practice.py", line 18, in __call__
    self.pagetemplate =  PageTemplate(args.Sfile)
  File "/home/aqsa/anaconda3/lib/python3.6/site-packages/chameleon/zpt/template.py", line 202, in __init__
    super(PageTemplate, self).__init__(body, **config)
  File "/home/aqsa/anaconda3/lib/python3.6/site-packages/chameleon/template.py", line 132, in __init__
    self.write(body)
  File "/home/aqsa/anaconda3/lib/python3.6/site-packages/chameleon/template.py", line 221, in write
    content_type = body.startswith('<?xml')
AttributeError: '_io.TextIOWrapper' object has no attribute 'startswith'
...