Skip to content

Commit ae4c2e2

Browse files
author
Whitie
committed
Added text option, for free text under the barcode. Fixed PEP 8 warnings.
1 parent e72dd2d commit ae4c2e2

9 files changed

Lines changed: 129 additions & 83 deletions

File tree

barcode/__init__.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# -*- coding: utf-8 -*-
22

3+
from barcode.errors import BarcodeNotFoundError
4+
from barcode.codex import Code39, PZN, Code128
5+
from barcode.ean import EAN8, EAN13, JAN
6+
from barcode.isxn import ISBN10, ISBN13, ISSN
7+
from barcode.upc import UPCA
8+
from barcode.itf import ITF
9+
310
"""
411
512
pyBarcode
@@ -11,11 +18,12 @@
1118
installed, the barcodes can also be rendered as images (all
1219
formats supported by PIL).
1320
"""
21+
__docformat__ = 'restructuredtext en'
1422

1523
__project__ = 'pyBarcode'
1624
__author__ = 'Thorsten Weimann'
17-
__copyright__ = '2010-2013, ' + __author__
18-
__author_email__ = 'weimann@ymail.com'
25+
__copyright__ = '2010-2016, ' + __author__
26+
__author_email__ = 'weimann.th@yahoo.com'
1927
__description__ = ('Create standard barcodes with Python. No external '
2028
'modules needed (optional PIL support included).')
2129
__version__ = '0.8'
@@ -34,13 +42,6 @@
3442
]
3543

3644

37-
from barcode.errors import BarcodeNotFoundError
38-
from barcode.codex import Code39, PZN, Code128
39-
from barcode.ean import EAN8, EAN13, JAN
40-
from barcode.isxn import ISBN10, ISBN13, ISSN
41-
from barcode.upc import UPCA
42-
from barcode.itf import ITF
43-
4445
try:
4546
_strbase = basestring # lint:ok
4647
except NameError:
@@ -86,14 +87,15 @@ def get_class(name):
8687
return get_barcode(name)
8788

8889

89-
def generate(name, code, writer=None, output=None, writer_options=None):
90+
def generate(name, code, writer=None, output=None, writer_options=None,
91+
text=None):
9092
options = writer_options or {}
9193
barcode = get_barcode(name, code, writer)
9294
if isinstance(output, _strbase):
93-
fullname = barcode.save(output, options)
95+
fullname = barcode.save(output, options, text)
9496
return fullname
9597
else:
96-
barcode.write(output, options)
98+
barcode.write(output, options, text)
9799

98100

99101
get_barcode = get

barcode/base.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def get_fullcode(self):
5252
"""
5353
raise NotImplementedError
5454

55-
def save(self, filename, options=None):
55+
def save(self, filename, options=None, text=None):
5656
"""Renders the barcode and saves it in `filename`.
5757
5858
:parameters:
@@ -61,15 +61,17 @@ def save(self, filename, options=None):
6161
extension).
6262
options : Dict
6363
The same as in `self.render`.
64+
text : str (unicode on Python 2)
65+
Text to render under the barcode.
6466
6567
:returns: The full filename with extension.
6668
:rtype: String
6769
"""
68-
output = self.render(options)
70+
output = self.render(options, text)
6971
_filename = self.writer.save(filename, output)
7072
return _filename
7173

72-
def write(self, fp, options=None):
74+
def write(self, fp, options=None, text=None):
7375
"""Renders the barcode and writes it to the file like object
7476
`fp`.
7577
@@ -78,26 +80,33 @@ def write(self, fp, options=None):
7880
Object to write the raw data in.
7981
options : Dict
8082
The same as in `self.render`.
83+
text : str (unicode on Python 2)
84+
Text to render under the barcode.
8185
"""
82-
output = self.render(options)
86+
output = self.render(options, text)
8387
if hasattr(output, 'tostring'):
8488
output.save(fp, format=self.writer.format)
8589
else:
8690
fp.write(output)
8791

88-
def render(self, writer_options=None):
92+
def render(self, writer_options=None, text=None):
8993
"""Renders the barcode using `self.writer`.
9094
9195
:parameters:
9296
writer_options : Dict
9397
Options for `self.writer`, see writer docs for details.
98+
text : str (unicode on Python 2)
99+
Text to render under the barcode.
94100
95101
:returns: Output of the writers render method.
96102
"""
97103
options = Barcode.default_writer_options.copy()
98104
options.update(writer_options or {})
99-
if options['write_text']:
100-
options['text'] = self.get_fullcode()
105+
if options['write_text'] or text is not None:
106+
if text is not None:
107+
options['text'] = text
108+
else:
109+
options['text'] = self.get_fullcode()
101110
self.writer.set_options(options)
102111
code = self.build()
103112
raw = Barcode.raw = self.writer.render(code)

barcode/codex.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22

33
from __future__ import unicode_literals
44

5+
from barcode.base import Barcode
6+
from barcode.charsets import code128, code39
7+
from barcode.errors import *
8+
59
"""Module: barcode.codex
610
711
:Provided barcodes: Code 39, Code 128, PZN
812
"""
913
__docformat__ = 'restructuredtext en'
1014

11-
from barcode.base import Barcode
12-
from barcode.charsets import code128, code39
13-
from barcode.errors import *
14-
1515

1616
# Sizes
1717
MIN_SIZE = 0.2
@@ -24,9 +24,10 @@ def check_code(code, name, allowed):
2424
if char not in allowed:
2525
wrong.append(char)
2626
if wrong:
27-
raise IllegalCharacterError('The following characters are not '
28-
'valid for {name}: {wrong}'.format(name=name,
29-
wrong=', '.join(wrong)))
27+
raise IllegalCharacterError(
28+
'The following characters are not valid for '
29+
'{name}: {wrong}'.format(name=name, wrong=', '.join(wrong))
30+
)
3031

3132

3233
class Code39(Barcode):

barcode/ean.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22

33
from __future__ import unicode_literals
44

5+
from barcode.base import Barcode
6+
from barcode.charsets import ean as _ean
7+
from barcode.errors import *
8+
59
"""Module: barcode.ean
610
711
:Provided barcodes: EAN-13, EAN-8, JAN
812
"""
9-
10-
from barcode.base import Barcode
11-
from barcode.charsets import ean as _ean
12-
from barcode.errors import *
13+
__docformat__ = 'restructuredtext en'
1314

1415
# Python 3
1516
try:
@@ -48,10 +49,13 @@ def __init__(self, ean, writer=None, **kwargs):
4849
raise NumberOfDigitsError('EAN must have {0} digits, not '
4950
'{1}.'.format(self.digits, len(ean)))
5051
self.ean = ean
51-
# If no checksum
52+
# If no checksum
5253
if no_checksum:
53-
# Add a thirteen char if given in parameter, otherwise pad with zero
54-
self.ean = '{0}{1}'.format(ean, ean[self.digits] if len(ean) > self.digits else 0)
54+
# Add a thirteen char if given in parameter,
55+
# otherwise pad with zero
56+
self.ean = '{0}{1}'.format(
57+
ean, ean[self.digits] if len(ean) > self.digits else 0
58+
)
5559
else:
5660
self.ean = '{0}{1}'.format(ean, self.calculate_checksum())
5761
self.writer = writer or Barcode.default_writer()

barcode/isxn.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from __future__ import unicode_literals
44

5+
from barcode.ean import EuropeanArticleNumber13
6+
from barcode.errors import *
7+
58
"""Module: barcode.isxn
69
710
:Provided barcodes: ISBN-13, ISBN-10, ISSN
@@ -27,9 +30,6 @@
2730
"""
2831
__docformat__ = 'restructuredtext en'
2932

30-
from barcode.ean import EuropeanArticleNumber13
31-
from barcode.errors import *
32-
3333

3434
class InternationalStandardBookNumber13(EuropeanArticleNumber13):
3535
"""Initializes new ISBN-13 barcode.

barcode/itf.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,21 @@
22

33
from __future__ import unicode_literals
44

5+
from barcode.base import Barcode
6+
from barcode.charsets import itf
7+
from barcode.errors import *
8+
59
"""Module: barcode.itf
610
711
:Provided barcodes: Interleaved 2 of 5
812
"""
913
__docformat__ = 'restructuredtext en'
1014

11-
from barcode.base import Barcode
12-
from barcode.charsets import itf
13-
from barcode.errors import *
1415

1516
MIN_SIZE = 0.2
1617
MIN_QUIET_ZONE = 6.4
1718

19+
1820
class ITF(Barcode):
1921
"""Initializes a new ITF instance.
2022
@@ -35,7 +37,7 @@ class ITF(Barcode):
3537
def __init__(self, code, writer=None, narrow=2, wide=5):
3638
if not code.isdigit():
3739
raise IllegalCharacterError('ITF code can only contain numbers.')
38-
#Length must be even, prepend 0 if necessary
40+
# Length must be even, prepend 0 if necessary
3941
if len(code) % 2 != 0:
4042
code = '0' + code
4143
self.code = code
@@ -73,6 +75,7 @@ def build(self):
7375
return [raw]
7476

7577
def render(self, writer_options):
76-
options = dict(module_width=MIN_SIZE/self.narrow, quiet_zone=MIN_QUIET_ZONE)
78+
options = dict(module_width=MIN_SIZE/self.narrow,
79+
quiet_zone=MIN_QUIET_ZONE)
7780
options.update(writer_options or {})
7881
return Barcode.render(self, options)

barcode/pybarcode.py

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import print_function
44

55
import os
6-
import sys
76

87
import barcode
98

@@ -42,61 +41,74 @@ def list_types(args, parser=None):
4241
def create_barcode(args, parser):
4342
args.type = args.type.upper()
4443
if args.type != 'SVG' and args.type not in IMG_FORMATS:
45-
parser.error('Unknown type {type}. Try list action for available '
46-
'types.'.format(type=args.type))
44+
parser.error(
45+
'Unknown type {type}. Try list action for available '
46+
'types.'.format(type=args.type)
47+
)
4748
args.barcode = args.barcode.lower()
4849
if args.barcode not in barcode.PROVIDED_BARCODES:
49-
parser.error('Unknown barcode {bc}. Try list action for available '
50-
'barcodes.'.format(bc=args.barcode))
50+
parser.error(
51+
'Unknown barcode {bc}. Try list action for available '
52+
'barcodes.'.format(bc=args.barcode)
53+
)
5154
if args.type != 'SVG':
5255
opts = dict(format=args.type)
5356
writer = ImageWriter()
5457
else:
5558
opts = dict(compress=args.compress)
5659
writer = SVGWriter()
5760
out = os.path.normpath(os.path.abspath(args.output))
58-
name = barcode.generate(args.barcode, args.code, writer, out, opts)
61+
name = barcode.generate(args.barcode, args.code, writer, out, opts,
62+
args.text)
5963
print('New barcode saved as {0}.'.format(name))
6064

6165

6266
def main():
6367
msg = []
6468
if ImageWriter is None:
65-
msg.append('Image output disabled (PIL not found), --type option '
66-
'disabled.')
69+
msg.append(
70+
'Image output disabled (PIL not found), --type option disabled.'
71+
)
6772
else:
68-
msg.append('Image output enabled, use --type option to give image '
69-
'format (png, jpeg, ...).')
73+
msg.append(
74+
'Image output enabled, use --type option to give image '
75+
'format (png, jpeg, ...).'
76+
)
7077
if QtCore is None:
7178
msg.append('PyQt not found, gui action disabled.')
7279
else:
7380
msg.append('PyQt found. Use gui action to get a simple GUI.')
74-
parser = ArgumentParser(description=barcode.__description__,
75-
epilog=' '.join(msg))
81+
parser = ArgumentParser(
82+
description=barcode.__description__, epilog=' '.join(msg)
83+
)
7684
parser.add_argument('-v', '--version', action='version',
77-
version='%(prog)s ' + barcode.__release__)
85+
version='%(prog)s ' + barcode.__release__)
7886
subparsers = parser.add_subparsers(title='Actions')
7987
create_parser = subparsers.add_parser('create', help='Create a barcode '
80-
'with the given options.')
88+
'with the given options.')
8189
create_parser.add_argument('code', help='Code to render as barcode.')
8290
create_parser.add_argument('output', help='Filename for output '
83-
'without extension, e. g. mybarcode.')
84-
create_parser.add_argument('-c', '--compress', action='store_true',
85-
help='Compress output, only recognized if type is svg.')
91+
'without extension, e. g. mybarcode.')
92+
create_parser.add_argument(
93+
'-c', '--compress', action='store_true',
94+
help='Compress output, only recognized if type is svg.'
95+
)
8696
create_parser.add_argument('-b', '--barcode', help='Barcode to use '
87-
'[default: %(default)s].')
97+
'[default: %(default)s].')
98+
create_parser.add_argument('--text', help='Text to show under the '
99+
'barcode.')
88100
if ImageWriter is not None:
89101
create_parser.add_argument('-t', '--type', help='Type of output '
90-
'[default: %(default)s].')
102+
'[default: %(default)s].')
91103
list_parser = subparsers.add_parser('list', help='List available '
92-
'image and code types.')
104+
'image and code types.')
93105
list_parser.set_defaults(func=list_types)
94106
if QtCore is not None:
95107
gui_parser = subparsers.add_parser('gui', help='Opens a simple '
96-
'PyQt GUI to create barcodes.')
108+
'PyQt GUI to create barcodes.')
97109
gui_parser.set_defaults(func=open_gui)
98110
create_parser.set_defaults(type='svg', compress=False, func=create_barcode,
99-
barcode='code39')
111+
barcode='code39', text=None)
100112
args = parser.parse_args()
101113
args.func(args, parser)
102114

0 commit comments

Comments
 (0)