[chirp_devel] [PATCH 2/3] Use logging in chirp/*.py (#2347)

Zach Welch
Sun Mar 1 21:19:38 PST 2015


# HG changeset patch
# User Zach Welch <zach at mandolincreekfarm.com>
# Fake Node ID 88a26664c446bc143ce4085fd8ae296c3ebafeff

Use logging in chirp/*.py (#2347)


diff --git a/chirp/bitwise.py b/chirp/bitwise.py
index 544ac4f..39efe8f 100644
--- a/chirp/bitwise.py
+++ b/chirp/bitwise.py
@@ -59,10 +59,13 @@
 
 import struct
 import os
+import logging
 
 from chirp import bitwise_grammar
 from chirp.memmap import MemoryMap
 
+LOG = logging.getLogger(__name__)
+
 
 class ParseError(Exception):
     """Indicates an error parsing a definition"""
@@ -770,8 +773,8 @@ class Processor:
             bitsleft -= bits
 
         if bitsleft:
-            print "WARNING: %i trailing bits unaccounted for in %s" % \
-                  (bitsleft, bitfield)
+            LOG.warn("WARNING: %i trailing bits unaccounted for in %s" %
+                     (bitsleft, bitfield))
 
         return bytes
 
@@ -866,7 +869,8 @@ class Processor:
         elif name == "seek":
             self._offset += int(value, 0)
         elif name == "printoffset":
-            print "%s: %i (0x%08X)" % (value[1:-1], self._offset, self._offset)
+            LOG.debug("%s: %i (0x%08X)" %
+                      (value[1:-1], self._offset, self._offset))
 
     def parse_block(self, lang):
         for t, d in lang:
diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py
index 1566cc5..16cbf40 100644
--- a/chirp/chirp_common.py
+++ b/chirp/chirp_common.py
@@ -423,8 +423,8 @@ class Memory:
         try:
             self.number = int(vals[0])
         except:
-            print "Loc: %s" % vals[0]
-            raise errors.InvalidDataError("Location is not a valid integer")
+            raise errors.InvalidDataError(
+                "Location '%s' is not a valid integer" % vals[0])
 
         self.name = vals[1]
 
diff --git a/chirp/detect.py b/chirp/detect.py
index 580670f..b590fb5 100644
--- a/chirp/detect.py
+++ b/chirp/detect.py
@@ -14,10 +14,13 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import serial
+import logging
 
 from chirp import errors, icf, directory, ic9x_ll
 from chirp import kenwood_live, icomciv
 
+LOG = logging.getLogger(__name__)
+
 
 def _icom_model_data_to_rclass(md):
     for _rtype, rclass in directory.DRV_TO_RADIO.items():
@@ -40,7 +43,7 @@ def _detect_icom_radio(ser):
         md = icf.get_model_data(ser)
         return _icom_model_data_to_rclass(md)
     except errors.RadioError, e:
-        print e
+        LOG.error(e)
 
     # ICOM IC-91/92 Live-mode radios @ 4800/38400 baud
 
@@ -77,9 +80,8 @@ def detect_icom_radio(port):
 
     ser.close()
 
-    print "Auto-detected %s %s on %s" % (result.VENDOR,
-                                         result.MODEL,
-                                         port)
+    LOG.info("Auto-detected %s %s on %s" %
+             (result.VENDOR, result.MODEL, port))
 
     return result
 
diff --git a/chirp/directory.py b/chirp/directory.py
index 7b529e6..d89708f 100644
--- a/chirp/directory.py
+++ b/chirp/directory.py
@@ -45,7 +45,7 @@ def enable_reregistrations():
     exception"""
     global ALLOW_DUPS
     if not ALLOW_DUPS:
-        print "NOTE: driver re-registration enabled"
+        LOG.info("driver re-registration enabled")
     ALLOW_DUPS = True
 
 
@@ -106,8 +106,7 @@ def icf_to_image(icf_file, img_file):
         f.write(img_data)
         f.close()
     else:
-        print "Unsupported model data:"
-        print util.hexprint(mdata)
+        LOG.error("Unsupported model data: %s" % util.hexprint(mdata))
         raise Exception("Unsupported model")
 
 
@@ -128,7 +127,7 @@ def get_radio_by_image(image_file):
     if os.path.exists(image_file) and icf.is_icf_file(image_file):
         tempf = tempfile.mktemp()
         icf_to_image(image_file, tempf)
-        print "Auto-converted %s -> %s" % (image_file, tempf)
+        LOG.info("Auto-converted %s -> %s" % (image_file, tempf))
         image_file = tempf
 
     if os.path.exists(image_file):
diff --git a/chirp/generic_csv.py b/chirp/generic_csv.py
index 66a6005..e7c3c93 100644
--- a/chirp/generic_csv.py
+++ b/chirp/generic_csv.py
@@ -15,9 +15,12 @@
 
 import os
 import csv
+import logging
 
 from chirp import chirp_common, errors, directory
 
+LOG = logging.getLogger(__name__)
+
 
 class OmittedHeaderError(Exception):
     """Internal exception to signal that a column has been omitted"""
@@ -190,9 +193,8 @@ class CSVRadio(chirp_common.FileBackedRadio, chirp_common.IcomDstarSupport):
                 continue
 
             if len(header) > len(line):
-                print "Line %i has %i columns, expected %i" % (lineno,
-                                                               len(line),
-                                                               len(header))
+                LOG.error("Line %i has %i columns, expected %i",
+                          lineno, len(line), len(header))
                 self.errors.append("Column number mismatch on line %i" %
                                    lineno)
                 continue
@@ -202,7 +204,7 @@ class CSVRadio(chirp_common.FileBackedRadio, chirp_common.IcomDstarSupport):
                 if mem.number is None:
                     raise Exception("Invalid Location field" % lineno)
             except Exception, e:
-                print "Line %i: %s" % (lineno, e)
+                LOG.error("Line %i: %s", lineno, e)
                 self.errors.append("Line %i: %s" % (lineno, e))
                 continue
 
@@ -211,7 +213,7 @@ class CSVRadio(chirp_common.FileBackedRadio, chirp_common.IcomDstarSupport):
             good += 1
 
         if not good:
-            print self.errors
+            LOG.error(self.errors)
             raise errors.InvalidDataError("No channels found")
 
     def save(self, filename=None):
diff --git a/chirp/generic_xml.py b/chirp/generic_xml.py
index 8f96278..06c5da9 100644
--- a/chirp/generic_xml.py
+++ b/chirp/generic_xml.py
@@ -15,9 +15,12 @@
 
 import os
 import libxml2
+import logging
 
 from chirp import chirp_common, errors, xml_ll, platform, directory
 
+LOG = logging.getLogger(__name__)
+
 
 def validate_doc(doc):
     """Validate the document"""
@@ -30,8 +33,8 @@ def validate_doc(doc):
         ctx = libxml2.schemaNewParserCtxt(path)
         schema = ctx.schemaParse()
     except libxml2.parserError, e:
-        print "Unable to load schema: %s" % e
-        print "Path: %s" % path
+        LOG.error("Unable to load schema: %s" % e)
+        LOG.error("Path: %s" % path)
         raise errors.RadioError("Unable to load schema")
 
     del ctx
@@ -43,16 +46,19 @@ def validate_doc(doc):
         errs.append("ERROR: %s" % msg)
 
     def _wrn(msg, *_args):
-        print "WARNING: %s" % msg
         warnings.append("WARNING: %s" % msg)
 
     validctx = schema.schemaNewValidCtxt()
     validctx.setValidityErrorHandler(_err, _wrn)
     err = validctx.schemaValidateDoc(doc)
-    print os.linesep.join(warnings)
+    for w in warnings:
+        LOG.warn(w)
     if err:
-        print "---DOC---\n%s\n------" % doc.serialize(format=1)
-        print os.linesep.join(errs)
+        for l in ["--- DOC ---",
+                  doc.serialize(format=1).split("\n"),
+                  "-----------",
+                  errs]:
+            LOG.error(l)
         raise errors.RadioError("Schema error")
 
 
diff --git a/chirp/import_logic.py b/chirp/import_logic.py
index 04f81ba..c2ed867 100644
--- a/chirp/import_logic.py
+++ b/chirp/import_logic.py
@@ -13,8 +13,11 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+import logging
 from chirp import chirp_common, errors
 
+LOG = logging.getLogger(__name__)
+
 
 class ImportError(Exception):
     """An import error"""
@@ -255,7 +258,7 @@ def import_bank(dst_radio, src_radio, dst_mem, src_mem):
     for index in src_indexes:
         try:
             bank = dst_banks[index]
-            print "Adding memory to bank %s" % bank
+            LOG.debug("Adding memory to bank %s" % bank)
             dst_bm.add_memory_to_mapping(dst_mem, bank)
             if isinstance(dst_bm, chirp_common.MappingModelIndexInterface):
                 dst_bm.set_memory_index(dst_mem, bank,
diff --git a/chirp/memmap.py b/chirp/memmap.py
index 73285bf..af0706c 100644
--- a/chirp/memmap.py
+++ b/chirp/memmap.py
@@ -24,7 +24,7 @@ class MemoryMap:
     def __init__(self, data):
         self._data = list(data)
 
-    def printable(self, start=None, end=None, printit=True):
+    def printable(self, start=None, end=None):
         """Return a printable representation of the memory map"""
         if not start:
             start = 0
@@ -34,9 +34,6 @@ class MemoryMap:
 
         string = util.hexprint(self._data[start:end])
 
-        if printit:
-            print string
-
         return string
 
     def get(self, start, length=1):
diff --git a/chirp/platform.py b/chirp/platform.py
index fc142c8..32285a5 100644
--- a/chirp/platform.py
+++ b/chirp/platform.py
@@ -17,8 +17,11 @@ import os
 import sys
 import glob
 import re
+import logging
 from subprocess import Popen
 
+LOG = logging.getLogger(__name__)
+
 
 def win32_comports_bruteforce():
     import win32file
@@ -265,7 +268,7 @@ class UnixPlatform(Platform):
         # time, however, I'll throw it here
         if sys.platform == "darwin":
             if "DISPLAY" not in os.environ:
-                print "Forcing DISPLAY for MacOS"
+                LOG.info("Forcing DISPLAY for MacOS")
                 os.environ["DISPLAY"] = ":0"
 
             os.environ["PANGO_RC_FILE"] = "../Resources/etc/pango/pangorc"
@@ -282,13 +285,13 @@ class UnixPlatform(Platform):
             pid2 = os.fork()
             if pid2 == 0:
                 editor = _unix_editor()
-                print "calling `%s %s'" % (editor, path)
+                LOG.debug("calling `%s %s'" % (editor, path))
                 os.execlp(editor, editor, path)
             else:
                 sys.exit(0)
         else:
             os.waitpid(pid1, 0)
-            print "Exec child exited"
+            LOG.debug("Exec child exited")
 
     def open_html_file(self, path):
         os.system("firefox '%s'" % path)
@@ -350,7 +353,7 @@ class Win32Platform(Platform):
             ports = list(comports())
         except Exception, e:
             if comports != win32_comports_bruteforce:
-                print "Failed to detect win32 serial ports: %s" % e
+                LOG.error("Failed to detect win32 serial ports: %s" % e)
                 ports = win32_comports_bruteforce()
         return natural_sorted([port for port, name, url in ports])
 
@@ -366,7 +369,7 @@ class Win32Platform(Platform):
         try:
             fname, _, _ = win32gui.GetOpenFileNameW(Filter=typestrs)
         except Exception, e:
-            print "Failed to get filename: %s" % e
+            LOG.error("Failed to get filename: %s" % e)
             return None
 
         return str(fname)
@@ -397,7 +400,7 @@ class Win32Platform(Platform):
                                                     DefExt=def_ext,
                                                     Filter=typestrs)
         except Exception, e:
-            print "Failed to get filename: %s" % e
+            LOG.error("Failed to get filename: %s" % e)
             return None
 
         return str(fname)
@@ -409,7 +412,7 @@ class Win32Platform(Platform):
             pidl, _, _ = shell.SHBrowseForFolder()
             fname = shell.SHGetPathFromIDList(pidl)
         except Exception, e:
-            print "Failed to get directory: %s" % e
+            LOG.error("Failed to get directory: %s" % e)
             return None
 
         return str(fname)
diff --git a/chirp/radioreference.py b/chirp/radioreference.py
index e7bae27..d52284e 100644
--- a/chirp/radioreference.py
+++ b/chirp/radioreference.py
@@ -13,7 +13,11 @@
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+import logging
 from chirp import chirp_common, errors
+
+LOG = logging.getLogger(__name__)
+
 try:
     from suds.client import Client
     from suds import WebFault
@@ -78,9 +82,9 @@ class RadioReferenceRadio(chirp_common.NetworkSourceRadio):
         status.max += len(county.agencyList)
 
         for cat in county.cats:
-            print "Fetching category:", cat.cName
+            LOG.debug("Fetching category:", cat.cName)
             for subcat in cat.subcats:
-                print "\t", subcat.scName
+                LOG.debug("\t", subcat.scName)
                 result = self._client.service.getSubcatFreqs(subcat.scid,
                                                              self._auth)
                 self._freqs += result
@@ -92,9 +96,9 @@ class RadioReferenceRadio(chirp_common.NetworkSourceRadio):
             for cat in agency.cats:
                 status.max += len(cat.subcats)
             for cat in agency.cats:
-                print "Fetching category:", cat.cName
+                LOG.debug("Fetching category:", cat.cName)
                 for subcat in cat.subcats:
-                    print "\t", subcat.scName
+                    LOG.debug("\t", subcat.scName)
                     result = self._client.service.getSubcatFreqs(subcat.scid,
                                                                  self._auth)
                     self._freqs += result
@@ -146,8 +150,7 @@ class RadioReferenceRadio(chirp_common.NetworkSourceRadio):
                     mem.tmode = "DTCS"
                     mem.dtcs = int(tone)
                 else:
-                    print "Error: unsupported tone"
-                    print freq
+                    LOG.error("Error: unsupported tone: %s" % freq)
         try:
             mem.mode = self._get_mode(freq.mode)
         except KeyError:
diff --git a/chirp/settings.py b/chirp/settings.py
index 5d8f3ee..a435d1f 100644
--- a/chirp/settings.py
+++ b/chirp/settings.py
@@ -114,7 +114,6 @@ class RadioSettingValueFloat(RadioSettingValue):
         if value is None:
             value = self._current
         fmt_string = "%%.%if" % self._pre
-        print fmt_string
         return fmt_string % value
 
     def set_value(self, value):




More information about the chirp_devel mailing list