Script with docx-python does not save the new file

1

I have the following problem, I have the following code which is responsible for sending the data to the imprimir_ticket module:

from es import imprimir_ticket

def productos(self):
    lista_01 = [] 
    pago = self.Cantidad.text()
    if lista1 == []:
        QMessageBox.critical(None,"Error \n\n","Ningun elemento en la lista de ventas \t",QMessageBox.Ok)
    elif pago.isdigit() == False:
        QMessageBox.critical(None,"Error \n\n","El tipo de cambio no es valido \t",QMessageBox.Ok)
    else:   
        for i in lista1:
            self.producto_especifico_id(i,sucursal)
            if len(i) == 4:
                ref  =db.reference('/Productos_Bar')
                r11 = ref.get()
                for key in r11.items():
                    res = key[1]['id']
                    if res == i:
                        new_ref = key[0]
                        ref_s = db.reference('/Productos_Bar/'+str(new_ref))
                        r12 = ref_s.get()
                        for key in r12.items():
                            if key[0] == 'producto':
                                prod = key[1]

                            elif key[0] == 'precio':
                                prec = ' $'+key[1]

                        lister =[i,' ',prod,prec] 
                        lista_01.append(lister)
                        imprimir_ticket(lista_01)

and this is the module that is responsible for generating the file:

en.py

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import time
time = str(time.strftime("%H-%M-%S"))


def imprimir_ticket(lista_items):
    doc = Document()
    doc.add_heading('                   Grupo Exxe',0)
    for item in lista_items:
        parrafo = doc.add_paragraph(item)
        parrafo_formato = parrafo.paragraph_format
        parrafo_formato.left_indent = Pt(155)
        parrafo_formato.right_indent = Pt(155)

    doc.add_page_break()
    doc.save('C:/Users/Angel/Desktop/'+time+'.docx')

The problem is that trying to execute the script again does not generate the new document, it only generates a new document if I close the whole program and return it open.

    
asked by Mystic_Force 19.08.2018 в 22:54
source

1 answer

1

It is not that he does not generate the document, it is that he overwrites it because the name is the same. When a module imports the code in the global space that is not under if __name__ == "__main__": it is executed at the same moment of the import .

Your variable time is a global variable which is initialized at the time you import the module ( from es import imprimir_ticket ) in the other module, in successive calls to the function this value will be the same until the module is reimported.

Do not make this variable global (in fact spend a lot of care with global variables, they should only be used when it really comes, for example constants). In principle it should be a local variable to the function so that each time you call it, the time is updated and the corresponding document is created with that time.

from pathlib import Path
import time

from docx import Document
from docx.shared import Inches, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT


def imprimir_ticket(lista_items):
    current_time = time.strftime("%H-%M-%S")
    doc = Document()
    doc.add_heading('                   Grupo Exxe',0)
    for item in lista_items:
        parrafo = doc.add_paragraph(item)
        parrafo_formato = parrafo.paragraph_format
        parrafo_formato.left_indent = Pt(155)
        parrafo_formato.right_indent = Pt(155)

    doc.add_page_break()
    doc.save(Path("C:/Users/Angel/Desktop/").joinpath(current_time).with_suffix(".docx")))

Obviously, when closing and re-executing the program, the module is re-imported, the variable time is created again and it is initialized with the current time, so the first call to the function does not give problems ( removing that the time will be the initialization of the program, not the call to the function).

Some observations:

  • No data is passed to the other module, you import the module and you use a function defined in the.

  • time.strftime already returns a string, casting is not necessary.

  • On the other hand, time is a very bad name for a variable when you are importing the module time with import time ... You are masking the module just imported with your variable, from that moment the identifier time does not refer to the module time , it is a string ... In a possible second call to time.strftime we will find a AttributeError .

answered by 19.08.2018 / 23:43
source