Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Sergio Pulgarin
Stephan Sokolow
Thijs Triemstra
Thomas van den Berg
tuxmaster
vendryan
Yaisel Hurtado
ysuolmai
Expand Down
4 changes: 2 additions & 2 deletions examples/codepage_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ def print_codepage(printer, codepage):

# Table header
printer.set(font="b")
printer._raw(" {}\n".format(sep.join(map(lambda s: hex(s)[2:], range(0, 16)))))
printer._raw(f" {sep.join(map(lambda s: hex(s)[2:], range(0, 16)))}\n")
printer.set()

# The table
for x in range(0, 16):
# First column
printer.set(font="b")
printer._raw("{} ".format(hex(x)[2:]))
printer._raw(f"{hex(x)[2:]} ")
printer.set()

for y in range(0, 16):
Expand Down
10 changes: 3 additions & 7 deletions src/escpos/capabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
logger = logging.getLogger(__name__)

pickle_dir = environ.get("ESCPOS_CAPABILITIES_PICKLE_DIR", mkdtemp())
pickle_path = path.join(
pickle_dir, "{v}.capabilities.pickle".format(v=platform.python_version())
)
pickle_path = path.join(pickle_dir, f"{platform.python_version()}.capabilities.pickle")
# get a temporary file from importlib_resources if no file is specified in env
file_manager = ExitStack()
atexit.register(file_manager.close)
Expand Down Expand Up @@ -114,9 +112,7 @@ def get_font(self, font) -> int:
"""
font = {"a": 0, "b": 1}.get(font, font)
if not six.text_type(font) in self.fonts:
raise NotSupported(
'"{}" is not a valid font in the current profile'.format(font)
)
raise NotSupported(f'"{font}" is not a valid font in the current profile')
return font

def get_columns(self, font):
Expand Down Expand Up @@ -158,7 +154,7 @@ def get_profile_class(name: str) -> Type[BaseProfile]:
profiles: Dict[str, Any] = CAPABILITIES["profiles"]
profile_data = profiles[name]
profile_name = clean(name)
class_name = "{}{}Profile".format(profile_name[0].upper(), profile_name[1:])
class_name = f"{profile_name[0].upper()}{profile_name[1:]}Profile"
new_class = type(class_name, (BaseProfile,), {"profile_data": profile_data})
CLASS_CACHE[name] = new_class

Expand Down
4 changes: 1 addition & 3 deletions src/escpos/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,7 @@ def load(self, config_path=None):

if not self._printer_name or not hasattr(printer, self._printer_name):
raise exceptions.ConfigSyntaxError(
'Printer type "{printer_name}" is invalid'.format(
printer_name=self._printer_name,
)
f'Printer type "{self._printer_name}" is invalid'
)

self._has_loaded = True
Expand Down
34 changes: 12 additions & 22 deletions src/escpos/escpos.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def image(
max_width = int(self.profile.profile_data["media"]["width"]["pixels"])

if im.width > max_width:
raise ImageWidthError("{} > {}".format(im.width, max_width))
raise ImageWidthError(f"{im.width} > {max_width}")

if center:
im.center(max_width)
Expand Down Expand Up @@ -420,9 +420,7 @@ def _int_low_high(inp_number: int, out_bytes: int) -> bytes:
raise ValueError("Can only output 1-4 bytes")
if not 0 <= inp_number <= max_input:
raise ValueError(
"Number too large. Can only output up to {0} in {1} bytes".format(
max_input, out_bytes
)
f"Number too large. Can only output up to {max_input} in {out_bytes} bytes"
)
outp = b""
for _ in range(0, out_bytes):
Expand Down Expand Up @@ -711,21 +709,15 @@ def _hw_barcode(
if not function_type or not BARCODE_TYPES.get(function_type.upper()):
raise BarcodeTypeError(
(
"Barcode '{bc}' not valid for barcode function type "
"{function_type}"
).format(
bc=bc,
function_type=function_type,
f"Barcode '{bc}' not valid for barcode function type "
f"{function_type}"
)
)
bc_types = BARCODE_TYPES[function_type.upper()]

if check and not self.check_barcode(bc, code):
raise BarcodeCodeError(
("Barcode '{code}' not in a valid format for type '{bc}'").format(
code=code,
bc=bc,
)
f"Barcode '{code}' not in a valid format for type '{bc}'"
)

# Align Bar Code()
Expand All @@ -735,12 +727,12 @@ def _hw_barcode(
if 1 <= height <= 255:
self._raw(BARCODE_HEIGHT + six.int2byte(height))
else:
raise BarcodeSizeError("height = {height}".format(height=height))
raise BarcodeSizeError(f"height = {height}")
# Width
if 2 <= width <= 6:
self._raw(BARCODE_WIDTH + six.int2byte(width))
else:
raise BarcodeSizeError("width = {width}".format(width=width))
raise BarcodeSizeError(f"width = {width}")
# Font
if font.upper() == "B":
self._raw(BARCODE_FONT_B)
Expand Down Expand Up @@ -833,9 +825,7 @@ def _sw_barcode(
# Check if barcode type exists
if barcode_type not in barcode.PROVIDED_BARCODES:
raise BarcodeTypeError(
"Barcode type {} not supported by software barcode renderer".format(
barcode_type
)
f"Barcode type {barcode_type} not supported by software barcode renderer"
)

# Render the barcode
Expand Down Expand Up @@ -878,7 +868,7 @@ def textln(self, txt=""):
:param txt: text to be printed with a newline
:raises: :py:exc:`~escpos.exceptions.TextError`
"""
self.text("{}\n".format(txt))
self.text(f"{txt}\n")

def ln(self, count=1):
"""Print a newline or more.
Expand Down Expand Up @@ -1426,17 +1416,17 @@ def writelines(self, text, **kwargs):
lines = text
else:
lines = [
"{0}".format(text),
f"{text}",
]

# TODO check unicode handling
# TODO flush? or on print? (this should prob rather be handled by the _raw-method)
for line in lines:
self.printer.set(**params)
if isinstance(text, six.text_type):
self.printer.text("{0}\n".format(line))
self.printer.text(f"{line}\n")
else:
self.printer.text("{0}\n".format(line))
self.printer.text(f"{line}\n")

def close(self):
"""Close printer.
Expand Down
32 changes: 13 additions & 19 deletions src/escpos/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of BarcodeTypeError."""
return "No Barcode type is defined ({msg})".format(msg=self.msg)
return f"No Barcode type is defined ({self.msg})"


class BarcodeSizeError(Error):
Expand All @@ -97,7 +97,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of BarcodeSizeError."""
return "Barcode size is out of range ({msg})".format(msg=self.msg)
return f"Barcode size is out of range ({self.msg})"


class BarcodeCodeError(Error):
Expand All @@ -122,7 +122,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of BarcodeCodeError."""
return "No Barcode code was supplied ({msg})".format(msg=self.msg)
return f"No Barcode code was supplied ({self.msg})"


class ImageSizeError(Error):
Expand All @@ -145,9 +145,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of ImageSizeError."""
return "Image height is longer than 255px and can't be printed ({msg})".format(
msg=self.msg
)
return f"Image height is longer than 255px and can't be printed ({self.msg})"


class ImageWidthError(Error):
Expand All @@ -170,7 +168,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of ImageWidthError."""
return "Image width is too large ({msg})".format(msg=self.msg)
return f"Image width is too large ({self.msg})"


class TextError(Error):
Expand All @@ -194,9 +192,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of TextError."""
return "Text string must be supplied to the text() method ({msg})".format(
msg=self.msg
)
return f"Text string must be supplied to the text() method ({self.msg})"


class CashDrawerError(Error):
Expand All @@ -220,7 +216,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of CashDrawerError."""
return "Valid pin must be set to send pulse ({msg})".format(msg=self.msg)
return f"Valid pin must be set to send pulse ({self.msg})"


class TabPosError(Error):
Expand All @@ -247,9 +243,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of TabPosError."""
return "Valid tab positions must be in the range 0 to 16 ({msg})".format(
msg=self.msg
)
return f"Valid tab positions must be in the range 0 to 16 ({self.msg})"


class CharCodeError(Error):
Expand All @@ -273,7 +267,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of CharCodeError."""
return "Valid char code must be set ({msg})".format(msg=self.msg)
return f"Valid char code must be set ({self.msg})"


class DeviceNotFoundError(Error):
Expand Down Expand Up @@ -345,7 +339,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of SetVariableError."""
return "Set variable out of range ({msg})".format(msg=self.msg)
return f"Set variable out of range ({self.msg})"


# Configuration errors
Expand All @@ -372,7 +366,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of ConfigNotFoundError."""
return "Configuration not found ({msg})".format(msg=self.msg)
return f"Configuration not found ({self.msg})"


class ConfigSyntaxError(Error):
Expand All @@ -396,7 +390,7 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of ConfigSyntaxError."""
return "Configuration syntax is invalid ({msg})".format(msg=self.msg)
return f"Configuration syntax is invalid ({self.msg})"


class ConfigSectionMissingError(Error):
Expand All @@ -420,4 +414,4 @@ def __init__(self, msg=""):

def __str__(self):
"""Return string representation of ConfigSectionMissingError."""
return "Configuration section is missing ({msg})".format(msg=self.msg)
return f"Configuration section is missing ({self.msg})"
12 changes: 5 additions & 7 deletions src/escpos/magicencode.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def get_encoding_name(self, encoding):
if encoding not in self.codepages:
raise ValueError(
(
'Encoding "{}" cannot be used for the current profile. '
"Valid encodings are: {}"
).format(encoding, ",".join(self.codepages.keys()))
f'Encoding "{encoding}" cannot be used for the current profile. '
f'Valid encodings are: {",".join(self.codepages.keys())}'
)
)
return encoding

Expand Down Expand Up @@ -88,7 +88,7 @@ def _get_codepage_char_list(encoding):
# Non-encodable character, just skip it
pass
return encodable_chars
raise LookupError("Can't find a known encoding for {}".format(encoding))
raise LookupError(f"Can't find a known encoding for {encoding}")

def _get_codepage_char_map(self, encoding):
"""Get codepage character map.
Expand Down Expand Up @@ -294,9 +294,7 @@ def write_with_encoding(self, encoding, text):
"""Write the text and inject necessary codepage switches."""
if text is not None and type(text) is not six.text_type:
raise Error(
"The supplied text has to be unicode, but is of type {type}.".format(
type=type(text)
)
f"The supplied text has to be unicode, but is of type {type(text)}."
)

# We always know the current code page; if the new codepage
Expand Down