From 4d9fa6c345591d671057e59619c2301fcef0a389 2012-11-09 11:42:35 From: Lance Edgar Date: 2012-11-09 11:42:35 Subject: [PATCH] add timeout support to CommandNetworkPrinter --- diff --git a/rattail/labels.py b/rattail/labels.py index ea529cf23e7cd0a9116aa749b4032f1efd01169e..c64ad5e9f358aa50a523cef66d753e00c194c9e6 100644 --- a/rattail/labels.py +++ b/rattail/labels.py @@ -146,6 +146,7 @@ class CommandFilePrinter(CommandPrinter): settings = OrderedDict() settings['address'] = "IP Address" settings['port'] = "Port" +settings['timeout'] = "Timeout" class CommandNetworkPrinter(CommandPrinter): """ @@ -157,6 +158,7 @@ class CommandNetworkPrinter(CommandPrinter): required_settings = settings address = None port = None + timeout = None def print_labels(self, labels, progress=None): """ @@ -185,12 +187,22 @@ class CommandNetworkPrinter(CommandPrinter): if footer: data.write('%s\n' % '\n'.join(footer)) - # Must pass byte-strings (not unicode) to this function. - sock = socket.create_connection((str(self.address), str(self.port))) - bytes = sock.send(data.getvalue()) - sock.close() - data.close() - return bytes + try: + timeout = int(self.timeout) + except ValueError: + timeout = socket.getdefaulttimeout() + + try: + # Must pass byte-strings (not unicode) to this function. + sock = socket.create_connection((str(self.address), str(self.port)), timeout) + except socket.timeout: + raise LabelPrintingError("Can't communicate with printer.") + else: + bytes = sock.send(data.getvalue()) + sock.close() + return bytes + finally: + data.close() class LabelFormatter(edbob.Object):