st-ten-1/src/components/os_label_printer.py
germano2239 09ce995866 dev gg
2022-07-26 16:09:01 +02:00

55 lines
2.0 KiB
Python

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