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
7 changes: 6 additions & 1 deletion .github/workflows/pythonpackage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ jobs:
python -m pip install --upgrade pip
pip install flake8 pytest tox tox-gh-actions
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Check sorting of imports
uses: isort/isort-action@master
with:
requirementsFiles: "requirements.txt doc/requirements.txt"
Comment thread
patkan marked this conversation as resolved.
sortPaths: "./doc ./src ./examples ./test ./setup.py"
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
Expand All @@ -50,4 +55,4 @@ jobs:
files: ./coverage.xml,!./cache
flags: unittests
name: coverage-tox-${{ matrix.python-version }}
verbose: true
verbose: true
3 changes: 1 addition & 2 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

import sys
from importlib.metadata import version as imp_version

on_rtd = os.getenv("READTHEDOCS") == "True"
Expand Down
2 changes: 1 addition & 1 deletion examples/barcodes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Example for printing barcodes."""
from escpos.printer import Usb


# Adapt to your needs
p = Usb(0x0416, 0x5011, profile="TM-T88II")

Expand Down
14 changes: 8 additions & 6 deletions examples/codepage_tables.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
"""Prints code page tables.
"""
"""Prints code page tables."""


import six
import sys

import six

from escpos import printer
from escpos.constants import (
CODEPAGE_CHANGE,
ESC,
CTL_LF,
CTL_FF,
CTL_CR,
CTL_FF,
CTL_HT,
CTL_LF,
CTL_VT,
ESC,
)


def main():
"""Init printer and print codepage tables."""
dummy = printer.Dummy()

dummy.hw("init")
Expand All @@ -34,6 +35,7 @@ def main():


def print_codepage(printer, codepage):
"""Print a codepage."""
if codepage.isdigit():
codepage = int(codepage)
printer._raw(CODEPAGE_CHANGE + six.int2byte(codepage))
Expand Down
5 changes: 4 additions & 1 deletion examples/docker-flask/app.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
from escpos.printer import CupsPrinter
"""Example for a flask application."""
from flask import Flask

from escpos.printer import CupsPrinter

# Initialize Flask app
app = Flask(__name__)


@app.route("/", methods=["GET"])
def do_print():
"""Print."""
# p = Usb(0x04b8, 0x0e28, 0)
p = CupsPrinter(host="localhost", port=631, printer_name="TM-T20III")
p.text("Hello World\n")
Expand Down
1 change: 0 additions & 1 deletion examples/docker-flask/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ argcomplete==3.0.8
blinker==1.6.2
click==8.1.3
Flask==2.3.2
future==0.18.3
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
Expand Down
2 changes: 2 additions & 0 deletions examples/qr_code.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""Print example QR codes."""
import sys

from escpos.printer import Usb


def usage():
"""Print information on usage."""
print("usage: qr_code.py <content>")


Expand Down
2 changes: 1 addition & 1 deletion examples/software_barcode.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Example file for software barcodes."""
from escpos.printer import Usb


# Adapt to your needs
p = Usb(0x0416, 0x5011, profile="POS-5890")

Expand Down
33 changes: 18 additions & 15 deletions examples/weather.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
#!/usr/bin/python
"""Weather forecast example.

Adapted script from Adafruit
Weather forecast for Raspberry Pi w/Adafruit Mini Thermal Printer.
Retrieves data from DarkSky.net's API, prints current conditions and
forecasts for next two days.
Weather example using nice bitmaps.
Written by Adafruit Industries. MIT license.
Adapted and enhanced for escpos library by MrWunderbar666

# Adapted script from Adafruit
# Weather forecast for Raspberry Pi w/Adafruit Mini Thermal Printer.
# Retrieves data from DarkSky.net's API, prints current conditions and
# forecasts for next two days.
# Weather example using nice bitmaps.
# Written by Adafruit Industries. MIT license.
# Adapted and enhanced for escpos library by MrWunderbar666
Icons taken from https://adamwhitcroft.com/climacons/
Check out his github: https://github.com/AdamWhitcroft/climacons
"""

# Icons taken from https://adamwhitcroft.com/climacons/
# Check out his github: https://github.com/AdamWhitcroft/climacons


from datetime import datetime
import calendar
import urllib
import json
import time
import os
import time
import urllib
from datetime import datetime

from escpos.printer import Usb

""" Setting up the main pathing """
"""Set up the main pathing."""
this_dir, this_filename = os.path.split(__file__)
GRAPHICS_PATH = os.path.join(this_dir, "graphics/climacons/")

Expand All @@ -38,13 +39,14 @@


def forecast_icon(idx):
"""Get right icon for forecast."""
icon = data["daily"]["data"][idx]["icon"]
image = GRAPHICS_PATH + icon + ".png"
return image


# Dumps one forecast line to the printer
def forecast(idx):
"""Dump one forecast line to the printer."""
date = datetime.fromtimestamp(int(data["daily"]["data"][idx]["time"]))
day = calendar.day_name[date.weekday()]
lo = data["daily"]["data"][idx]["temperatureMin"]
Expand Down Expand Up @@ -73,6 +75,7 @@ def forecast(idx):


def icon():
"""Get icon."""
icon = data["currently"]["icon"]
image = GRAPHICS_PATH + icon + ".png"
return image
Expand Down
12 changes: 12 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
[tool.black]
extend-exclude = 'capabilities-data'

[tool.isort]
profile = "black"

[tool.pytest.ini_options]
minversion = "6.0"
addopts = "--doctest-modules --cov escpos --cov-report=xml"
testpaths = [
"test",
"src",
Comment thread
patkan marked this conversation as resolved.
"src/escpos",
"escpos",
]
4 changes: 1 addition & 3 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ project_urls =
Release Notes = https://github.com/python-escpos/python-escpos/releases

[options]
python_requires = >=3.6
python_requires = >=3.8
zip_safe = false
include_package_data = true
install_requires =
Expand All @@ -46,7 +46,6 @@ install_requires =
PyYAML
argparse
argcomplete
future
importlib_resources
setup_requires = setuptools_scm
tests_require =
Expand All @@ -65,4 +64,3 @@ tests_require =
exclude = .git,.tox,.github,.eggs,__pycache__,doc/conf.py,build,dist,capabilities-data,test,src/escpos/constants.py
max-line-length = 120
extend-ignore = E203, W503
# future-imports = absolute_import, division, print_function, unicode_literals # we are not there yet
15 changes: 10 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
"""Setup script for python package."""

import os
import sys
from setuptools import find_packages, setup

from setuptools import find_packages, setup

base_dir = os.path.dirname(__file__)
src_dir = os.path.join(base_dir, "src")
Expand All @@ -14,14 +15,18 @@


def read(fname):
"""read file from same path as setup.py"""
"""Read file from same path as setup.py."""
return open(os.path.join(os.path.dirname(__file__), fname)).read()


setuptools_scm_template = """\
# coding: utf-8
# file generated by setuptools_scm
# don't change, don't track in version control
#!/usr/bin/python
# -*- coding: utf-8 -*-
\"\"\"Version identifier.

file generated by setuptools_scm
don't change, don't track in version control
\"\"\"

version = '{version}'
"""
Expand Down
4 changes: 1 addition & 3 deletions src/escpos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
"""
python-escpos enables you to manipulate escpos-printers
"""
"""python-escpos enables you to manipulate escpos-printers."""

__all__ = ["constants", "escpos", "exceptions", "printer"]

Expand Down
48 changes: 27 additions & 21 deletions src/escpos/capabilities.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import re
from os import environ, path
"""Handler for capabilities data."""
import atexit
import pickle
import logging
import pickle
import platform
import re
import time
import importlib_resources

import six
import yaml

from contextlib import ExitStack
from os import environ, path
from tempfile import mkdtemp
import platform
from typing import Any, Dict, Optional

from typing import Any, Dict
import importlib_resources
import six
import yaml

logging.basicConfig()
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -60,9 +59,7 @@


class NotSupported(Exception):
"""Raised if a requested feature is not supported by the
printer profile.
"""
"""Raised if a requested feature is not supported by the printer profile."""

pass

Expand All @@ -80,11 +77,13 @@ class BaseProfile(object):
profile_data: Dict[str, Any] = {}

def __getattr__(self, name):
"""Get a data element from the profile."""
return self.profile_data[name]

def get_font(self, font) -> int:
"""Return the escpos index for `font`. Makes sure that
the requested `font` is valid.
"""Return the escpos index for `font`.

Makes sure that the requested `font` is valid.
"""
font = {"a": 0, "b": 1}.get(font, font)
if not six.text_type(font) in self.fonts:
Expand All @@ -107,9 +106,10 @@ def get_code_pages(self):
return {v: k for k, v in self.codePages.items()}


def get_profile(name: str = None, **kwargs):
"""Get the profile by name; if no name is given, return the
default profile.
def get_profile(name: Optional[str] = None, **kwargs):
"""Get a profile by name.

If no name is given, return the default profile.
"""
if isinstance(name, Profile):
return name
Expand All @@ -122,7 +122,9 @@ def get_profile(name: str = None, **kwargs):


def get_profile_class(name: str):
"""For the given profile name, load the data from the external
"""Load a profile class.

For the given profile name, load the data from the external
database, then generate dynamically a class.
"""
if name not in CLASS_CACHE:
Expand All @@ -136,6 +138,7 @@ def get_profile_class(name: str):


def clean(s):
"""Clean profile name."""
# Remove invalid characters
s = re.sub("[^0-9a-zA-Z_]", "", s)
# Remove leading characters until we find a letter or underscore
Expand All @@ -144,17 +147,20 @@ def clean(s):


class Profile(get_profile_class("default")):
"""
For users, who want to provide their profile
"""Profile class for user usage.

For users, who want to provide their own profile.
"""

def __init__(self, columns=None, features=None):
"""Initialize profile."""
super(Profile, self).__init__()

self.columns = columns
self.features = features or {}

def get_columns(self, font):
"""Get column count of printer."""
if self.columns is not None:
return self.columns

Expand Down
Loading