class Printer(): | |
""" | |
Print thing with my ESCPOS printer | |
""" | |
def text(self, text): | |
with open('/dev/usb/lp0', 'wb') as lp0: | |
lp0.write(text.encode('cp437')) | |
lp0.write(b'\n') | |
def command(self, command): | |
with open('/dev/usb/lp0', 'wb') as lp0: | |
lp0.write(command) | |
lp0.write(b'\n') | |
def style(command_before, command_after): | |
""" | |
Send a command before and a command after | |
""" | |
def decorator(func): | |
def wrapper(self, text): | |
print(self) | |
print(text) | |
self.command(command_before) | |
func(text) | |
self.command(command_after) | |
return wrapper | |
return decorator | |
@style((b'\x1D\x42\x31'), (b'\x1D\x42\x32')) #print white on black | |
@style((b'\x1D\x21\x34'), (b'\x1D\y21\x00')) #print bigger | |
def title(self, title_text): | |
self.text(title_text) | |
class _BeforeAfterContext(object): | |
def __init__(self, printer, before, after): | |
self._printer = printer | |
self._before = before | |
self._after = after | |
def __enter__(self): | |
self._printer.write_line(self._before) | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if exc_val is None: | |
# Don't send if an exception occurred | |
return False | |
self._printer.write_line(self._after) | |
class Printer(): | |
def __init__(self, device): | |
self._device = device | |
def write_line(self, data): | |
self._device.write(data + b'\n') | |
def style(self, before, after): | |
return _BeforeAfterContext(self, before, after) | |
with open('/dev/usb/lp0', 'rb') as lp0: | |
printer = Printer(lp0) | |
with printer.style(b'\x1D\x42\x31', b'\x1D\x42\x32'): #print white on black | |
with printer.style(b'\x1D\x21\x34', b'\x1D\y21\x00'): #print bigger | |
printer.write_line(title_text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment