Debian Codegraph @

brother_ql/cli.py

raw
1 #!/usr/bin/env python
2
3 # Python standard library
4 from __future__ import print_function
5 import logging
6
7 # external dependencies
8 import click
9
10 # imports from this very package
11 from brother_ql.devicedependent import models, label_sizes, label_type_specs, DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL
12 from brother_ql.backends import available_backends, backend_factory
13
14
15 logger = logging.getLogger('brother_ql')
16
17
18 printer_help = "The identifier for the printer. This could be a string like tcp://192.168.1.21:9100 for a networked printer or usb://0x04f9:0x2015/000M6Z401370 for a printer connected via USB."
19 @click.group()
20 @click.option('-b', '--backend', type=click.Choice(available_backends), envvar='BROTHER_QL_BACKEND')
21 @click.option('-m', '--model', type=click.Choice(models), envvar='BROTHER_QL_MODEL')
22 @click.option('-p', '--printer', metavar='PRINTER_IDENTIFIER', envvar='BROTHER_QL_PRINTER', help=printer_help)
23 @click.option('--debug', is_flag=True)
24 @click.version_option()
25 @click.pass_context
26 def cli(ctx, *args, **kwargs):
27 """ Command line interface for the brother_ql Python package. """
28
29 backend = kwargs.get('backend', None)
30 model = kwargs.get('model', None)
31 printer = kwargs.get('printer', None)
32 debug = kwargs.get('debug')
33
34 # Store the general CLI options in the context meta dictionary.
35 # The name corresponds to the second half of the respective envvar:
36 ctx.meta['MODEL'] = model
37 ctx.meta['BACKEND'] = backend
38 ctx.meta['PRINTER'] = printer
39
40 logging.basicConfig(level='DEBUG' if debug else 'INFO')
41
42 @cli.command()
43 @click.pass_context
44 def discover(ctx):
45 """ find connected label printers """
46 backend = ctx.meta.get('BACKEND', 'pyusb')
47 discover_and_list_available_devices(backend)
48
49 def discover_and_list_available_devices(backend):
50 from brother_ql.backends.helpers import discover
51 available_devices = discover(backend_identifier=backend)
52 from brother_ql.output_helpers import log_discovered_devices, textual_description_discovered_devices
53 log_discovered_devices(available_devices)
54 print(textual_description_discovered_devices(available_devices))
55
56 @cli.group()
57 @click.pass_context
58 def info(ctx, *args, **kwargs):
59 """ list available labels, models etc. """
60
61 @info.command(name='models')
62 @click.pass_context
63 def models_cmd(ctx, *args, **kwargs):
64 """
65 List the choices for --model
66 """
67 print('Supported models:')
68 for model in models: print(" " + model)
69
70 @info.command()
71 @click.pass_context
72 def labels(ctx, *args, **kwargs):
73 """
74 List the choices for --label
75 """
76 from brother_ql.output_helpers import textual_label_description
77 print(textual_label_description(label_sizes))
78
79 @info.command()
80 @click.pass_context
81 def env(ctx, *args, **kwargs):
82 """
83 print debug info about running environment
84 """
85 import sys, platform, os, shutil
86 from pkg_resources import get_distribution, working_set
87 print("\n##################\n")
88 print("Information about the running environment of brother_ql.")
89 print("(Please provide this information when reporting any issue.)\n")
90 # computer
91 print("About the computer:")
92 for attr in ('platform', 'processor', 'release', 'system', 'machine', 'architecture'):
93 print(' * '+attr.title()+':', getattr(platform, attr)())
94 # Python
95 print("About the installed Python version:")
96 py_version = str(sys.version).replace('\n', ' ')
97 print(" *", py_version)
98 # brother_ql
99 print("About the brother_ql package:")
100 pkg = get_distribution('brother_ql')
101 print(" * package location:", pkg.location)
102 print(" * package version: ", pkg.version)
103 try:
104 cli_loc = shutil.which('brother_ql')
105 except:
106 cli_loc = 'unknown'
107 print(" * brother_ql CLI path:", cli_loc)
108 # brother_ql's requirements
109 print("About the requirements of brother_ql:")
110 fmt = " {req:14s} | {spec:10s} | {ins_vers:17s}"
111 print(fmt.format(req='requirement', spec='requested', ins_vers='installed version'))
112 print(fmt.format(req='-' * 14, spec='-'*10, ins_vers='-'*17))
113 requirements = list(pkg.requires())
114 requirements.sort(key=lambda x: x.project_name)
115 for req in requirements:
116 proj = req.project_name
117 req_pkg = get_distribution(proj)
118 spec = ' '.join(req.specs[0]) if req.specs else 'any'
119 print(fmt.format(req=proj, spec=spec, ins_vers=req_pkg.version))
120 print("\n##################\n")
121
122 @cli.command('print', short_help='Print a label')
123 @click.argument('images', nargs=-1, type=click.File('rb'), metavar='IMAGE [IMAGE] ...')
124 @click.option('-l', '--label', type=click.Choice(label_sizes), envvar='BROTHER_QL_LABEL', help='The label (size, type - die-cut or endless). Run `brother_ql info labels` for a full list including ideal pixel dimensions.')
125 @click.option('-r', '--rotate', type=click.Choice(('auto', '0', '90', '180', '270')), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.')
126 @click.option('-t', '--threshold', type=float, default=70.0, help='The threshold value (in percent) to discriminate between black and white pixels.')
127 @click.option('-d', '--dither', is_flag=True, help='Enable dithering when converting the image to b/w. If set, --threshold is meaningless.')
128 @click.option('-c', '--compress', is_flag=True, help='Enable compression (if available with the model). Label creation can take slightly longer but the resulting instruction size is normally considerably smaller.')
129 @click.option('--red', is_flag=True, help='Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red.')
130 @click.option('--600dpi', 'dpi_600', is_flag=True, help='Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi.')
131 @click.option('--lq', is_flag=True, help='Print with low quality (faster). Default is high quality.')
132 @click.option('--no-cut', is_flag=True, help="Don't cut the tape after printing the label.")
133 @click.pass_context
134 def print_cmd(ctx, *args, **kwargs):
135 """ Print a label of the provided IMAGE. """
136 backend = ctx.meta.get('BACKEND', 'pyusb')
137 model = ctx.meta.get('MODEL')
138 printer = ctx.meta.get('PRINTER')
139 from brother_ql.conversion import convert
140 from brother_ql.backends.helpers import send
141 from brother_ql.raster import BrotherQLRaster
142 qlr = BrotherQLRaster(model)
143 qlr.exception_on_warning = True
144 kwargs['cut'] = not kwargs['no_cut']
145 del kwargs['no_cut']
146 instructions = convert(qlr=qlr, **kwargs)
147 send(instructions=instructions, printer_identifier=printer, backend_identifier=backend, blocking=True)
148
149 @cli.command(name='analyze', help='interpret a binary file containing raster instructions for the Brother QL-Series printers')
150 @click.argument('instructions', type=click.File('rb'))
151 @click.option('-f', '--filename-format', help="Filename format string. Default is: label{counter:04d}.png.")
152 @click.pass_context
153 def analyze_cmd(ctx, *args, **kwargs):
154 from brother_ql.reader import BrotherQLReader
155 br = BrotherQLReader(kwargs.get('instructions'))
156 if kwargs.get('filename_format'): br.filename_fmt = kwargs.get('filename_format')
157 br.analyse()
158
159 @cli.command(name='send', short_help='send an instruction file to the printer')
160 @click.argument('instructions', type=click.File('rb'))
161 @click.pass_context
162 def send_cmd(ctx, *args, **kwargs):
163 from brother_ql.backends.helpers import send
164 send(instructions=kwargs['instructions'].read(), printer_identifier=ctx.meta.get('PRINTER'), backend_identifier=ctx.meta.get('BACKEND'), blocking=True)
165
166 if __name__ == '__main__':
167 cli()