st-ten-1/src/components/os_label_printer.py

50 lines
1.8 KiB
Python
Raw Normal View History

2022-06-01 16:37:19 +00:00
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)
if "--sim-os-label-printer" in sys.argv:
self.simulate = True
def config_changed(self):
self.platform = self.config["label_printer"]["platform"]
# for windows:
# cmd
# wmic printer list brief
# powershell
# Get-Printer
# for cups (linux, osx)
# lpstat -p -d
self.printer = self.config["label_printer"]["printer"]
def print_label(self, template, archived):
# LOAD LABEL TEMPLATE
with open(f"config/label_templates/{template}.prn") as f:
label = f.read()
# LABEL PRINT
label = label.replace("$PH1", archived.barcode).replace("$PH2", archived.barcode)
label_file = "a"
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