REFACTOR fix minor PEP8 and similar mistakes

This commit is contained in:
Patrick Kanzler 2016-01-08 03:34:14 +01:00
parent 0e907644d9
commit f25521f22f
6 changed files with 47 additions and 30 deletions

View File

@ -1,2 +1,5 @@
import constants, escpos, exceptions, printer import constants
import escpos
import exceptions
import printer
__all__ = ["constants", "escpos", "exceptions", "printer"] __all__ = ["constants", "escpos", "exceptions", "printer"]

View File

@ -46,9 +46,11 @@ __license__ = "MIT"
import re import re
from escpos import printer from escpos import printer
epson = printer.Usb(0x0416, 0x5011) epson = printer.Usb(0x0416, 0x5011)
# TODO: Un-hardcode this # TODO: Un-hardcode this
def _print_text_file(path): def _print_text_file(path):
"""Print the given text file""" """Print the given text file"""
epson.set(align='left') epson.set(align='left')
@ -56,10 +58,12 @@ def _print_text_file(path):
for line in fobj: for line in fobj:
epson.text(line) epson.text(line)
def _print_image_file(path): def _print_image_file(path):
"""Print the given image file.""" """Print the given image file."""
epson.fullimage(path, histeq=False, width=384) epson.fullimage(path, histeq=False, width=384)
def print_files(args): def print_files(args):
"""The 'print' subcommand""" """The 'print' subcommand"""
for path in args.paths: for path in args.paths:
@ -74,6 +78,7 @@ def print_files(args):
KNOWN_BARCODE_TYPES = ['UPC-A', 'UPC-E', 'EAN13', 'ITF'] KNOWN_BARCODE_TYPES = ['UPC-A', 'UPC-E', 'EAN13', 'ITF']
re_barcode_escape = re.compile(r'^%(?P<type>\S+)\s(?P<data>[0-9X]+)$') re_barcode_escape = re.compile(r'^%(?P<type>\S+)\s(?P<data>[0-9X]+)$')
def echo(args): # pylint: disable=unused-argument def echo(args): # pylint: disable=unused-argument
"""TTY-like line-by-line keyboard-to-printer echo loop.""" """TTY-like line-by-line keyboard-to-printer echo loop."""
try: try:
@ -94,6 +99,7 @@ def echo(args): # pylint: disable=unused-argument
from PIL import Image, ImageDraw from PIL import Image, ImageDraw
def _stall_test(width, height): def _stall_test(width, height):
"""Generate a pattern to detect print glitches due to vertical stalling.""" """Generate a pattern to detect print glitches due to vertical stalling."""
img = Image.new('1', (width, height)) img = Image.new('1', (width, height))
@ -101,6 +107,7 @@ def _stall_test(width, height):
img.putpixel(pos, not sum(pos) % 10) img.putpixel(pos, not sum(pos) % 10)
return img return img
def _test_basic(): def _test_basic():
"""The original test code from python-escpos's Usage wiki page""" """The original test code from python-escpos's Usage wiki page"""
epson.set(align='left') epson.set(align='left')
@ -120,24 +127,26 @@ def _test_basic():
# Cut paper # Cut paper
epson.cut() epson.cut()
def _test_barcodes(): def _test_barcodes():
"""Print test barcodes for all ESCPOS-specified formats.""" """Print test barcodes for all ESCPOS-specified formats."""
for name, data in ( for name, data in (
# pylint: disable=bad-continuation # pylint: disable=bad-continuation
('UPC-A', '123456789012\x00'), ('UPC-A', '123456789012\x00'),
('UPC-E', '02345036\x00'), ('UPC-E', '02345036\x00'),
('EAN13', '1234567890128\x00'), ('EAN13', '1234567890128\x00'),
('EAN8', '12345670\x00'), ('EAN8', '12345670\x00'),
('CODE39', 'BARCODE12345678\x00'), ('CODE39', 'BARCODE12345678\x00'),
('ITF', '123456\x00'), ('ITF', '123456\x00'),
('CODABAR', 'A40156B'), ('CODABAR', 'A40156B'),
# TODO: CODE93 and CODE128 # TODO: CODE93 and CODE128
): ):
# TODO: Fix the library to restore old alignment somehow # TODO: Fix the library to restore old alignment somehow
epson.set(align='center') epson.set(align='center')
epson.text('\n%s\n' % name) epson.text('\n%s\n' % name)
epson.barcode(data, name, 64, 2, '', '') epson.barcode(data, name, 64, 2, '', '')
def _test_patterns(width=384, height=255): def _test_patterns(width=384, height=255):
"""Print a set of test patterns for raster image output.""" """Print a set of test patterns for raster image output."""
# Test our guess of the paper width # Test our guess of the paper width
@ -152,6 +161,7 @@ def _test_patterns(width=384, height=255):
epson.image(_stall_test(width, height)) epson.image(_stall_test(width, height))
epson.image(_stall_test(width / 2, height)) epson.image(_stall_test(width / 2, height))
def test(args): def test(args):
"""The 'test' subcommand""" """The 'test' subcommand"""
if args.barcodes: if args.barcodes:
@ -161,6 +171,7 @@ def test(args):
else: else:
_test_basic() _test_basic()
# }}} # }}}
def main(): def main():
@ -168,25 +179,26 @@ def main():
# pylint: disable=bad-continuation # pylint: disable=bad-continuation
import argparse import argparse
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description="Command-line interface to python-escpos") description="Command-line interface to python-escpos")
subparsers = parser.add_subparsers(title='subcommands') subparsers = parser.add_subparsers(title='subcommands')
echo_parser = subparsers.add_parser('echo', help='Echo the keyboard to ' echo_parser = subparsers.add_parser('echo', help='Echo the keyboard to '
'the printer line-by-line (Exit with Ctrl+C)') 'the printer line-by-line (Exit with Ctrl+C)')
echo_parser.set_defaults(func=echo) echo_parser.set_defaults(func=echo)
print_parser = subparsers.add_parser('print', help='Print the given files') print_parser = subparsers.add_parser('print', help='Print the given files')
print_parser.add_argument('--images', action='store_true', print_parser.add_argument('--images', action='store_true',
help="Provided files are images rather than text files.") help="Provided files are images rather than text files.")
print_parser.add_argument('paths', metavar='path', nargs='+') print_parser.add_argument('paths', metavar='path', nargs='+')
print_parser.set_defaults(func=print_files) print_parser.set_defaults(func=print_files)
test_parser = subparsers.add_parser('test', help='Print test patterns') test_parser = subparsers.add_parser('test', help='Print test patterns')
test_modes = test_parser.add_mutually_exclusive_group() test_modes = test_parser.add_mutually_exclusive_group()
test_modes.add_argument('--barcodes', action='store_true', test_modes.add_argument('--barcodes', action='store_true',
help="Test supported barcode types (Warning: Some printers must be " help="Test supported barcode types (Warning: Some printers must be "
"reset after attempting an unsupported barcode type.)") "reset after attempting an unsupported barcode type.)")
test_modes.add_argument('--patterns', action='store_true', test_modes.add_argument('--patterns', action='store_true',
help="Print test patterns") help="Print test patterns")
test_parser.set_defaults(func=test) test_parser.set_defaults(func=test)
@ -194,6 +206,7 @@ def main():
args = parser.parse_args() args = parser.parse_args()
args.func(args) args.func(args)
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -15,10 +15,8 @@ except ImportError:
from PIL import Image from PIL import Image
import qrcode import qrcode
import time
import textwrap import textwrap
import binascii import binascii
import os
import operator import operator
from .constants import * from .constants import *
@ -26,6 +24,7 @@ from .exceptions import *
from abc import ABCMeta, abstractmethod # abstract base class support from abc import ABCMeta, abstractmethod # abstract base class support
class Escpos(object): class Escpos(object):
""" ESC/POS Printer object """ ESC/POS Printer object
@ -64,9 +63,9 @@ class Escpos(object):
else: else:
image_border = 32 - (size % 32) image_border = 32 - (size % 32)
if (image_border % 2) == 0: if (image_border % 2) == 0:
return (round(image_border / 2), round(image_border / 2)) return round(image_border / 2), round(image_border / 2)
else: else:
return (round(image_border / 2), round((image_border / 2) + 1)) return round(image_border / 2), round((image_border / 2) + 1)
def _print_image(self, line, size): def _print_image(self, line, size):
""" Print formatted image """ Print formatted image
@ -221,16 +220,16 @@ class Escpos(object):
#self._raw(binascii.unhexlify(buf)) #self._raw(binascii.unhexlify(buf))
for y in range(height): for y in range(height):
for x in range(width): for x in range(width):
value = image.getpixel((x,y)) value = image.getpixel((x, y))
value = (value << 8) | value; value |= (value << 8)
if value == 0: if value == 0:
temp |= mask temp |= mask
mask = mask >> 1 mask >>= 1
i += 1 i += 1
if i == 8: if i == 8:
buf += ("%02X" % temp) buf += ("%02X" % temp)
mask = 0x80 mask = 0x80
i = 0 i = 0
temp = 0 temp = 0
@ -413,7 +412,7 @@ class Escpos(object):
:param columns: amount of columns :param columns: amount of columns
:return: None :return: None
""" """
colCount = self.columns if columns == None else columns colCount = self.columns if columns is None else columns
self.text(textwrap.fill(txt, colCount)) self.text(textwrap.fill(txt, colCount))
def set(self, align='left', font='a', text_type='normal', width=1, height=1, density=9): def set(self, align='left', font='a', text_type='normal', width=1, height=1, density=9):

View File

@ -153,6 +153,7 @@ class CharCodeError(Error):
def __str__(self): def __str__(self):
return "Valid char code must be set" return "Valid char code must be set"
class USBNotFoundError(Error): class USBNotFoundError(Error):
""" Device wasn't found (probably not plugged in) """ Device wasn't found (probably not plugged in)

View File

@ -13,7 +13,6 @@ import serial
import socket import socket
from .escpos import * from .escpos import *
from .constants import *
from .exceptions import * from .exceptions import *
@ -32,7 +31,7 @@ class Usb(Escpos):
:param out_ep: Output end point :param out_ep: Output end point
""" """
Escpos.__init__(self, *args, **kwargs) Escpos.__init__(self, *args, **kwargs)
self.idVendor = idVendor self.idVendor = idVendor
self.idProduct = idProduct self.idProduct = idProduct
self.interface = interface self.interface = interface
self.in_ep = in_ep self.in_ep = in_ep
@ -100,10 +99,10 @@ class Serial(Escpos):
:param dsrdtr: Hardware flow control (False to enable RTS/CTS) :param dsrdtr: Hardware flow control (False to enable RTS/CTS)
""" """
Escpos.__init__(self, *args, **kwargs) Escpos.__init__(self, *args, **kwargs)
self.devfile = devfile self.devfile = devfile
self.baudrate = baudrate self.baudrate = baudrate
self.bytesize = bytesize self.bytesize = bytesize
self.timeout = timeout self.timeout = timeout
self.parity = parity self.parity = parity
self.stopbits = stopbits self.stopbits = stopbits
self.xonxoff = xonxoff self.xonxoff = xonxoff
@ -208,9 +207,9 @@ class File(Escpos):
:param msg: arbitrary code to be printed :param msg: arbitrary code to be printed
""" """
if type(msg) is str: if type(msg) is str:
self.device.write(msg.encode()); self.device.write(msg.encode())
else: else:
self.device.write(msg); self.device.write(msg)
def __del__(self): def __del__(self):
""" Close system file """ """ Close system file """

View File

@ -5,10 +5,12 @@ import sys
from setuptools import setup from setuptools import setup
from setuptools.command.test import test as TestCommand from setuptools.command.test import test as TestCommand
def read(fname): 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() return open(os.path.join(os.path.dirname(__file__), fname)).read()
class Tox(TestCommand): class Tox(TestCommand):
"""proxy class that enables tox to be run with setup.py test""" """proxy class that enables tox to be run with setup.py test"""
user_options = [('tox-args=', 'a', "Arguments to pass to tox")] user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
@ -26,7 +28,7 @@ class Tox(TestCommand):
def run_tests(self): def run_tests(self):
"""run tox and pass on user-options""" """run tox and pass on user-options"""
#import here, cause outside the eggs aren't loaded # import here, cause outside the eggs aren't loaded
import tox import tox
import shlex import shlex
args = self.tox_args args = self.tox_args