import subprocess import sys from PyQt5.QtWidgets import QMessageBox from .component import Component class Os_Label_Printer(Component): def __init__(self, config=None, name=None): super().__init__(config=config, name=name, threaded=False) self.simulate = False if "--sim-os-label-printer" in sys.argv: self.simulate = True self.platform = "windows" def config_changed(self): self.platform = self.config[self.name]["platform"] # for windows: # cmd # wmic printer list brief # powershell # Get-Printer # for cups (linux, osx) # lpstat -p -d self.printer = self.config[self.name]["printer"] def print_label(self, template, context=None): if context is None: context = {} # LOAD LABEL TEMPLATE with open(f"config/label_templates/{str(template)}.prn", "r", errors="surrogateescape") as f: label = f.read() # LABEL PRINT label = label.format(**context) label_file = "tmp/label.prn" with open(label_file, "w", errors="surrogateescape") as f: label = f.write(label) if self.platform == "windows": cmd = f'print /d:"{self.printer}" "{label_file}"' elif self.platform == "cups": cmd = f'lp -d "{self.printer}" "{label_file}"' else: raise NotImplementedError(f"platform {self.platform!r} is not supported") if not self.simulate: p = subprocess.run(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True) # unsafe if p.returncode != 0: self.log.exception(f"failed to print: returncode: {p.returncode}\noutput:\n{p.stdout}") QMessageBox.critical( None, "Errore Stampante", f"Non e stato possibile stampare l'etichetta.\n\nErrore:\nreturncode: {p.returncode}\noutput:\n{p.stdout}" ) return False return True