[chirp_devel] [PATCH 0/3] Use logging facilities

These patches convert the chirp[cw] scripts, the main chirp modules, and the chirpui modules to use the new logging facilities. I took an educated guess at the correct levels to use. The only files left to update are the drivers, which I am postponing until after they are moved into their own subdirectory.
This series applies on top of the previous series that fixes all of the style issues.
Zach Welch (3): Use logging in chirp[cw] (#2347) Use logging in chirp/*.py (#2347) Use logging in chirpui/*.py (#2347)
chirp/bitwise.py | 10 +++++++--- chirp/chirp_common.py | 4 ++-- chirp/detect.py | 10 ++++++---- chirp/directory.py | 7 +++---- chirp/generic_csv.py | 12 +++++++----- chirp/generic_xml.py | 18 ++++++++++++------ chirp/import_logic.py | 5 ++++- chirp/memmap.py | 5 +---- chirp/platform.py | 17 ++++++++++------- chirp/radioreference.py | 15 +++++++++------ chirp/settings.py | 1 - chirpc | 16 ++++++++-------- chirpui/bandplans.py | 9 +++++++-- chirpui/bankedit.py | 6 +++++- chirpui/clone.py | 11 +++++++---- chirpui/common.py | 33 +++++++++++++++++---------------- chirpui/dstaredit.py | 13 ++++++++----- chirpui/editorset.py | 7 +++++-- chirpui/importdialog.py | 28 ++++++++++++++++------------ chirpui/inputdialog.py | 11 +++++++---- chirpui/memdetail.py | 5 ++++- chirpui/memedit.py | 29 ++++++++++++++++------------- chirpui/miscwidgets.py | 11 +++++++---- chirpui/radiobrowser.py | 5 ++++- chirpui/reporting.py | 6 +++--- chirpui/settingsedit.py | 9 ++++++--- chirpui/shiftdialog.py | 11 +++++++---- chirpw | 9 ++++++--- 28 files changed, 194 insertions(+), 129 deletions(-)

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 6226a149dce7276ec9885fa2d8b8b29ee48a1724
Use logging in chirp[cw] (#2347)
diff --git a/chirpc b/chirpc index 217ca9f..dae48f6 100755 --- a/chirpc +++ b/chirpc @@ -30,12 +30,12 @@ RADIOS = directory.DRV_TO_RADIO
def fail_unsupported(): - print "Operation not supported by selected radio" + LOG.error("Operation not supported by selected radio") sys.exit(1)
def fail_missing_mmap(): - print "mmap-only operation requires specification of an mmap file" + LOG.error("mmap-only operation requires specification of an mmap file") sys.exit(1)
@@ -196,7 +196,7 @@ if __name__ == "__main__": else: s = options.radio + ".img" else: - print "opening %s at %i" % (options.serial, rclass.BAUD_RATE) + LOG.info("opening %s at %i" % (options.serial, rclass.BAUD_RATE)) s = serial.Serial(port=options.serial, baudrate=rclass.BAUD_RATE, timeout=0.5) @@ -218,8 +218,8 @@ if __name__ == "__main__": if options.set_mem_dup != "+" and \ options.set_mem_dup != "-" and \ options.set_mem_dup != "": - print "Invalid duplex value `%s'" % options.set_mem_dup - print "Valid values are: '+', '-', ''" + LOG.error("Invalid duplex value `%s'" % options.set_mem_dup) + LOG.error("Valid values are: '+', '-', ''") sys.exit(1) else: _dup = options.set_mem_dup @@ -227,9 +227,9 @@ if __name__ == "__main__": _dup = None
if options.set_mem_mode: - print "Set mode: %s" % options.set_mem_mode + LOG.info("Set mode: %s" % options.set_mem_mode) if options.set_mem_mode not in chirp_common.MODES: - print "Invalid mode `%s'" + LOG.error("Invalid mode `%s'") sys.exit(1) else: _mode = options.set_mem_mode @@ -303,7 +303,7 @@ if __name__ == "__main__": if radio.sync_out(): print "Clone successful" else: - print "Clone failed" + LOG.error("Clone failed")
if options.mmap and isinstance(radio, chirp_common.CloneModeRadio): radio.save_mmap(options.mmap) diff --git a/chirpw b/chirpw index 353edc9..4131948 100755 --- a/chirpw +++ b/chirpw @@ -29,6 +29,9 @@ import os import locale import gettext import argparse +import logging + +LOG = logging.getLogger("chirpw")
execpath = platform.get_platform().executable_path() @@ -51,10 +54,10 @@ if manual_language and manual_language != "Auto": "French": "fr", } try: - print lang_codes[manual_language] + LOG.info("Language: %s", lang_codes[manual_language]) langs = [lang_codes[manual_language]] except KeyError: - print "Unsupported language `%s'" % manual_language + LOG.error("Unsupported language `%s'" % manual_language) else: lc, encoding = locale.getdefaultlocale() if (lc): @@ -125,7 +128,7 @@ if True: a = mainapp.ChirpMain()
for i in args.files: - print "Opening %s" % i + LOG.info("Opening %s", i) a.do_open(i)
a.show()

# HG changeset patch # User Zach Welch zach@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):

# HG changeset patch # User Zach Welch zach@mandolincreekfarm.com # Fake Node ID 97b55474aa774c71e371d647080cf78e184b4f5e
Use logging in chirpui/*.py (#2347)
diff --git a/chirpui/bandplans.py b/chirpui/bandplans.py index 9d34cd1..4096d78 100644 --- a/chirpui/bandplans.py +++ b/chirpui/bandplans.py @@ -14,10 +14,13 @@ # along with this program. If not, see http://www.gnu.org/licenses/.
import gtk +import logging from chirp import bandplan, bandplan_na, bandplan_au from chirp import bandplan_iaru_r1, bandplan_iaru_r2, bandplan_iaru_r3 from chirpui import inputdialog
+LOG = logging.getLogger(__name__) +
class BandPlans(object): def __init__(self, config): @@ -44,7 +47,8 @@ class BandPlans(object): # Check for duplicates. duplicates = [x for x in plan.BANDS if x == band] if len(duplicates) > 1: - print "Bandplan %s has duplicates %s" % (name, duplicates) + LOG.warn("Bandplan %s has duplicates %s" % + (name, duplicates)) # Add repeater inputs. rpt_input = band.inverse() if rpt_input not in plan.BANDS: @@ -102,6 +106,7 @@ class BandPlans(object): self._config.set_bool(shortname, selection == details[0], "bandplan") if selection == details[0]: - print "Selected band plan %s: %s" % (shortname, selection) + LOG.info("Selected band plan %s: %s" % + (shortname, selection))
d.destroy() diff --git a/chirpui/bankedit.py b/chirpui/bankedit.py index 009f726..82f6b30 100644 --- a/chirpui/bankedit.py +++ b/chirpui/bankedit.py @@ -16,12 +16,15 @@ import gtk import gobject import time +import logging
from gobject import TYPE_INT, TYPE_STRING, TYPE_BOOLEAN
from chirp import chirp_common from chirpui import common, miscwidgets
+LOG = logging.getLogger(__name__) +
class MappingNamesJob(common.RadioJob): def __init__(self, model, editor, cb): @@ -378,7 +381,8 @@ class MappingMembershipEditor(common.Editor): (min, max) = self._rf.memory_bounds for i in range(min, max+1): self.refresh_memory(i) - print "Got all %s info in %s" % (self._type, (time.time() - start)) + LOG.debug("Got all %s info in %s" % + (self._type, (time.time() - start)))
def refresh_mappings(self, and_memories=False): def got_mappings(): diff --git a/chirpui/clone.py b/chirpui/clone.py index 63f6f10..5050b0d 100644 --- a/chirpui/clone.py +++ b/chirpui/clone.py @@ -14,6 +14,7 @@ # along with this program. If not, see http://www.gnu.org/licenses/.
import threading +import logging import os
import gtk @@ -22,6 +23,8 @@ import gobject from chirp import platform, directory, detect, chirp_common from chirpui import miscwidgets, cloneprog, inputdialog, common, config
+LOG = logging.getLogger(__name__) + AUTO_DETECT_STRING = "Auto Detect (Icom Only)"
@@ -188,7 +191,7 @@ class CloneSettingsDialog(gtk.Dialog): common.show_error( _("Internal error: Unable to upload to {model}").format( model=model)) - print self.__vendors + LOG.info(self.__vendors) return None
conf = config.get("state") @@ -222,7 +225,7 @@ class CloneThread(threading.Thread): self.__cancelled = True
def run(self): - print "Clone thread started" + LOG.debug("Clone thread started")
gobject.idle_add(self.__progw.show)
@@ -237,7 +240,7 @@ class CloneThread(threading.Thread): emsg = None except Exception, e: common.log_exception() - print _("Clone failed: {error}").format(error=e) + LOG.error(_("Clone failed: {error}").format(error=e)) emsg = e
gobject.idle_add(self.__progw.hide) @@ -245,7 +248,7 @@ class CloneThread(threading.Thread): # NB: Compulsory close of the radio's serial connection self.__radio.pipe.close()
- print "Clone thread ended" + LOG.debug("Clone thread ended")
if self.__cback and not self.__cancelled: gobject.idle_add(self.__cback, self.__radio, emsg) diff --git a/chirpui/common.py b/chirpui/common.py index dcbbb3f..83a1a19 100644 --- a/chirpui/common.py +++ b/chirpui/common.py @@ -21,10 +21,13 @@ import threading import time import os import traceback +import logging
from chirp import errors from chirpui import reporting, config
+LOG = logging.getLogger(__name__) + CONF = config.get()
@@ -78,9 +81,7 @@ gobject.type_register(Editor)
def DBG(*args): if False: - print " ".join(args) - -VERBOSE = False + LOG.debug(" ".join(args))
class RadioJob: @@ -111,17 +112,17 @@ class RadioJob: DBG("Running %s (%s %s)" % (self.func, str(self.args), str(self.kwargs))) - if VERBOSE: - print self.desc + DBG(self.desc) result = func(*self.args, **self.kwargs) except errors.InvalidMemoryLocation, e: result = e except Exception, e: - print "Exception running RadioJob: %s" % e + LOG.error("Exception running RadioJob: %s" % e) log_exception() - print "Job Args: %s" % str(self.args) - print "Job KWArgs: %s" % str(self.kwargs) - print "Job Called from:%s%s" % (os.linesep, "".join(self.tb[:-1])) + LOG.error("Job Args: %s" % str(self.args)) + LOG.error("Job KWArgs: %s" % str(self.kwargs)) + LOG.error("Job Called from:%s%s" % + (os.linesep, "".join(self.tb[:-1]))) result = e
if self.cb: @@ -134,8 +135,8 @@ class RadioJob: try: func = getattr(self.target, self.func) except AttributeError, e: - print "No such radio function `%s' in %s" % (self.func, - self.target) + LOG.error("No such radio function `%s' in %s" % + (self.func, self.target)) return
self._execute(self.target, func) @@ -261,7 +262,7 @@ class RadioThread(threading.Thread, gobject.GObject): last_job_desc = job.desc self.unlock()
- print "RadioThread exiting" + LOG.debug("RadioThread exiting")
def log_exception(): @@ -270,9 +271,9 @@ def log_exception():
reporting.report_exception(traceback.format_exc(limit=30))
- print "-- Exception: --" - traceback.print_exc(limit=30, file=sys.stdout) - print "------" + LOG.error("-- Exception: --") + LOG.error(traceback.format_exc(limit=30)) + LOG.error("----------------")
def show_error(msg, parent=None): @@ -417,7 +418,7 @@ def show_diff_blob(title, result): except Exception: fontsize = 11 if fontsize < 4 or fontsize > 144: - print "Unsupported diff_fontsize %i. Using 11." % fontsize + LOG.info("Unsupported diff_fontsize %i. Using 11." % fontsize) fontsize = 11
lines = result.split(os.linesep) diff --git a/chirpui/dstaredit.py b/chirpui/dstaredit.py index 75d05b1..d58f74b 100644 --- a/chirpui/dstaredit.py +++ b/chirpui/dstaredit.py @@ -15,9 +15,12 @@
import gtk import gobject +import logging
from chirpui import common, miscwidgets
+LOG = logging.getLogger(__name__) + WIDGETW = 80 WIDGETH = 30
@@ -96,24 +99,24 @@ class DStarEditor(common.Editor): def __cs_changed(self, cse): job = None
- print "Callsigns: %s" % cse.get_callsigns() + LOG.debug("Callsigns: %s" % cse.get_callsigns()) if cse == self.editor_ucall: job = common.RadioJob(None, "set_urcall_list", cse.get_callsigns()) - print "Set urcall" + LOG.debug("Set urcall") elif cse == self.editor_rcall: job = common.RadioJob(None, "set_repeater_call_list", cse.get_callsigns()) - print "Set rcall" + LOG.debug("Set rcall") elif cse == self.editor_mcall: job = common.RadioJob(None, "set_mycall_list", cse.get_callsigns())
if job: - print "Submitting job to update call lists" + LOG.debug("Submitting job to update call lists") self.rthread.submit(job)
self.emit("changed") @@ -154,7 +157,7 @@ class DStarEditor(common.Editor): if self.loaded: return self.loaded = True - print "Loading callsigns..." + LOG.debug("Loading callsigns...")
def set_ucall(calls): self.editor_ucall.set_callsigns(calls) diff --git a/chirpui/editorset.py b/chirpui/editorset.py index 59d82ea..4695e8c 100644 --- a/chirpui/editorset.py +++ b/chirpui/editorset.py @@ -16,11 +16,14 @@ import os import gtk import gobject +import logging
from chirp import chirp_common, directory, generic_csv, generic_xml from chirpui import memedit, dstaredit, bankedit, common, importdialog from chirpui import inputdialog, reporting, settingsedit, radiobrowser, config
+LOG = logging.getLogger(__name__) +
class EditorSet(gtk.VBox): __gsignals__ = { @@ -220,7 +223,7 @@ class EditorSet(gtk.VBox): memedit.prefill()
def editor_changed(self, target_editor=None): - print "%s changed" % target_editor + LOG.debug("%s changed" % target_editor) if not isinstance(self.radio, chirp_common.LiveRadio): self.modified = True self.update_tab() @@ -252,7 +255,7 @@ class EditorSet(gtk.VBox): return
count = dialog.do_import(dst_rthread) - print "Imported %i" % count + LOG.debug("Imported %i" % count) dst_rthread._qunlock()
if count > 0: diff --git a/chirpui/importdialog.py b/chirpui/importdialog.py index dd4be6e..0d59472 100644 --- a/chirpui/importdialog.py +++ b/chirpui/importdialog.py @@ -16,10 +16,13 @@ import gtk import gobject import pango +import logging
from chirp import errors, chirp_common, generic_xml, import_logic from chirpui import common
+LOG = logging.getLogger(__name__) +
class WaitWindow(gtk.Window): def __init__(self, msg, parent=None): @@ -174,15 +177,15 @@ class ImportDialog(gtk.Dialog): mem = self.src_radio.get_memory(old) if isinstance(mem, chirp_common.DVMemory): if mem.dv_urcall not in ulist: - print "Adding %s to ucall list" % mem.dv_urcall + LOG.debug("Adding %s to ucall list" % mem.dv_urcall) ulist.append(mem.dv_urcall) ulist_changed = True if mem.dv_rpt1call not in rlist: - print "Adding %s to rcall list" % mem.dv_rpt1call + LOG.debug("Adding %s to rcall list" % mem.dv_rpt1call) rlist.append(mem.dv_rpt1call) rlist_changed = True if mem.dv_rpt2call not in rlist: - print "Adding %s to rcall list" % mem.dv_rpt2call + LOG.debug("Adding %s to rcall list" % mem.dv_rpt2call) rlist.append(mem.dv_rpt2call) rlist_changed = True
@@ -231,13 +234,13 @@ class ImportDialog(gtk.Dialog): if not dst_banks or not src_banks: raise Exception() except Exception: - print "One or more of the radios doesn't support banks" + LOG.error("One or more of the radios doesn't support banks") return
if not isinstance(self.dst_radio, generic_xml.XMLRadio) and \ len(dst_banks) != len(src_banks): - print "Source and destination radios have " + \ - "a different number of banks" + LOG.warn("Source and destination radios have " + "a different number of banks") else: self.dst_radio.set_banks(src_banks)
@@ -250,7 +253,7 @@ class ImportDialog(gtk.Dialog):
for old, new, name, comm in import_list: i += 1 - print "%sing %i -> %i" % (self.ACTION, old, new) + LOG.debug("%sing %i -> %i" % (self.ACTION, old, new))
src = self.src_radio.get_memory(old)
@@ -262,7 +265,7 @@ class ImportDialog(gtk.Dialog): "name": name, "comment": comm}) except import_logic.ImportError, e: - print e + LOG.error(e) error_messages[new] = str(e) continue
@@ -322,7 +325,7 @@ class ImportDialog(gtk.Dialog): column.set_cell_data_func(rend, self._render, k)
if k in self.tips.keys(): - print "Doing %s" % k + LOG.debug("Doing %s" % k) lab = gtk.Label(self.caps[k]) column.set_widget(lab) tips.set_tip(lab, self.tips[k]) @@ -512,10 +515,11 @@ class ImportDialog(gtk.Dialog): if mem and not mem.empty and number not in self.used_list: self.used_list.append(number) except errors.InvalidMemoryLocation: - print "Location %i empty or at limit of destination radio" % number + LOG.error("Location %i empty or at limit of destination radio" % + number) except errors.InvalidDataError, e: - print "Got error from radio, assuming %i beyond limits: %s" % \ - (number, e) + LOG.error("Got error from radio, assuming %i beyond limits: %s" % + (number, e))
def populate_list(self): start, end = self.src_radio.get_features().memory_bounds diff --git a/chirpui/inputdialog.py b/chirpui/inputdialog.py index a276c2d..d3f2828 100644 --- a/chirpui/inputdialog.py +++ b/chirpui/inputdialog.py @@ -14,10 +14,13 @@ # along with this program. If not, see http://www.gnu.org/licenses/.
import gtk +import logging
from miscwidgets import make_choice from chirpui import reporting
+LOG = logging.getLogger(__name__) +
class TextInputDialog(gtk.Dialog): def respond_ok(self, _): @@ -88,9 +91,9 @@ class ExceptionDialog(gtk.MessageDialog): import traceback import sys reporting.report_exception(traceback.format_exc(limit=30)) - print "--- Exception Dialog: %s ---" % exception - traceback.print_exc(limit=100, file=sys.stdout) - print "----------------------------" + LOG.error("--- Exception Dialog: %s ---" % exception) + LOG.error(traceback.format_exc(limit=100)) + LOG.error("----------------------------")
class FieldDialog(gtk.Dialog): @@ -105,7 +108,7 @@ class FieldDialog(gtk.Dialog): gtk.Dialog.__init__(self, **kwargs)
def response(self, _): - print "Blocking response" + LOG.debug("Blocking response") return
def add_field(self, label, widget, validator=None): diff --git a/chirpui/memdetail.py b/chirpui/memdetail.py index 120fe5b..0766230 100644 --- a/chirpui/memdetail.py +++ b/chirpui/memdetail.py @@ -15,10 +15,13 @@
import gtk import os +import logging
from chirp import chirp_common, settings from chirpui import miscwidgets, common
+LOG = logging.getLogger(__name__) + POL = ["NN", "NR", "RN", "RR"]
@@ -224,7 +227,7 @@ class MemoryDetailEditor(gtk.Dialog): try: _img = self._editors[name][2] except KeyError: - print self._editors.keys() + LOG.error(self._editors.keys()) if msg is None: _img.clear() self._tips.set_tip(_img, "") diff --git a/chirpui/memedit.py b/chirpui/memedit.py index 89f4d4b..7da07a2 100644 --- a/chirpui/memedit.py +++ b/chirpui/memedit.py @@ -27,11 +27,14 @@ from gobject import TYPE_INT, \ import gobject import pickle import os +import logging
from chirpui import common, shiftdialog, miscwidgets, config, memdetail from chirpui import bandplans from chirp import chirp_common, errors, directory, import_logic
+LOG = logging.getLogger(__name__) +
if __name__ == "__main__": import sys @@ -143,7 +146,7 @@ class MemoryEditor(common.Editor): offset *= -1
if dup not in self.choices[_("Duplex")]: - print "Duplex %s not supported by this radio" % dup + LOG.warn("Duplex %s not supported by this radio" % dup) return
if offset: @@ -155,7 +158,7 @@ class MemoryEditor(common.Editor): if ts in self.choices[_("Tune Step")]: self.store.set(iter, self.col(_("Tune Step")), ts) else: - print "Tune step %s not supported by this radio" % ts + LOG.warn("Tune step %s not supported by this radio" % ts)
def get_ts(path): return self.store.get(iter, self.col(_("Tune Step")))[0] @@ -164,19 +167,19 @@ class MemoryEditor(common.Editor): if mode in self.choices[_("Mode")]: self.store.set(iter, self.col(_("Mode")), mode) else: - print "Mode %s not supported by this radio (%s)" % ( - mode, self.choices[_("Mode")]) + LOG.warn("Mode %s not supported by this radio (%s)" % + (mode, self.choices[_("Mode")]))
def set_tone(tone): if tone in self.choices[_("Tone")]: self.store.set(iter, self.col(_("Tone")), tone) else: - print "Tone %s not supported by this radio" % tone + LOG.warn("Tone %s not supported by this radio" % tone)
try: new = chirp_common.parse_freq(new) except ValueError, e: - print e + LOG.error(e) new = None
if not self._features.has_nostep_tuning: @@ -335,7 +338,7 @@ class MemoryEditor(common.Editor): iter = self.store.get_iter(path) if not self.store.get(iter, self.col("_filled"))[0] and \ self.store.get(iter, self.col(_("Frequency")))[0] == 0: - print _("Editing new item, taking defaults") + LOG.error(_("Editing new item, taking defaults")) self.insert_new(iter)
colnum = self.col(cap) @@ -357,7 +360,7 @@ class MemoryEditor(common.Editor): new = funcs[cap](rend, path, new, colnum)
if new is None: - print _("Bad value for {col}: {val}").format(col=cap, val=new) + LOG.error(_("Bad value for {col}: {val}").format(col=cap, val=new)) return
if self.store.get_column_type(colnum) == TYPE_INT: @@ -451,7 +454,7 @@ class MemoryEditor(common.Editor): newpos, = store.get(_iter, self.col(_("Loc"))) newpos += delta
- print "Insert easy: %i" % delta + LOG.debug("Insert easy: %i" % delta)
mem = self.insert_new(iter, newpos) job = common.RadioJob(None, "set_memory", mem) @@ -962,7 +965,7 @@ class MemoryEditor(common.Editor): if i not in default_col_order: raise Exception() except Exception, e: - print e + LOG.error(e) col_order = default_col_order
non_editable = ["Loc"] @@ -1113,7 +1116,7 @@ class MemoryEditor(common.Editor): while iter: loc, = self.store.get(iter, self.col(_("Loc"))) if loc == number: - print "Deleting %i" % number + LOG.debug("Deleting %i" % number) # FIXME: Make the actual remove happen on callback self.store.remove(iter) job = common.RadioJob(None, "erase_memory", number) @@ -1299,7 +1302,7 @@ class MemoryEditor(common.Editor): for feature, colname in maybe_hide: if feature.startswith("has_"): supported = self._features[feature] - print "%s supported: %s" % (colname, supported) + LOG.info("%s supported: %s" % (colname, supported)) elif feature.startswith("valid_"): supported = len(self._features[feature]) != 0
@@ -1439,7 +1442,7 @@ class MemoryEditor(common.Editor): try: src_features, mem_list = pickle.loads(text) except Exception: - print "Paste failed to unpickle" + LOG.error("Paste failed to unpickle") return
if (paths[0][0] + len(mem_list)) > self._rows_in_store: diff --git a/chirpui/miscwidgets.py b/chirpui/miscwidgets.py index 723b8bf..768cfb6 100644 --- a/chirpui/miscwidgets.py +++ b/chirpui/miscwidgets.py @@ -18,9 +18,12 @@ import gobject import pango
import os +import logging
from chirp import platform
+LOG = logging.getLogger(__name__) +
class KeyedListWidget(gtk.HBox): __gsignals__ = { @@ -128,7 +131,7 @@ class KeyedListWidget(gtk.HBox): (store, iter) = self.__view.get_selection().get_selected() return store.get(iter, 0)[0] except Exception, e: - print "Unable to find selected: %s" % e + LOG.error("Unable to find selected: %s" % e) return None
def select_item(self, key): @@ -298,7 +301,7 @@ class ListWidget(gtk.HBox): (lst, iter) = self._view.get_selection().get_selected() lst.remove(iter) except Exception, e: - print "Unable to remove selected: %s" % e + LOG.error("Unable to remove selected: %s" % e)
def get_selected(self, take_default=False): (lst, iter) = self._view.get_selection().get_selected() @@ -416,7 +419,7 @@ class TreeWidget(ListWidget): elif isinstance(vals, tuple): self._add_item(parent, *vals) else: - print "Unknown type: %s" % vals + LOG.error("Unknown type: %s" % vals)
def set_values(self, vals): self._store.clear() @@ -586,7 +589,7 @@ class LatLonEntry(gtk.Entry): try: return self.parse_dms(string) except Exception, e: - print "DMS: %s" % e + LOG.error("DMS: %s" % e)
raise Exception("Invalid format")
diff --git a/chirpui/radiobrowser.py b/chirpui/radiobrowser.py index 14673f9..02cabbf 100644 --- a/chirpui/radiobrowser.py +++ b/chirpui/radiobrowser.py @@ -3,10 +3,13 @@ import gobject import pango import re import os +import logging
from chirp import bitwise from chirpui import common, config
+LOG = logging.getLogger(__name__) + CONF = config.get()
@@ -90,7 +93,7 @@ class FixedEntry(gtk.Entry): except Exception: fontsize = 10 if fontsize < 4 or fontsize > 144: - print "Unsupported browser_fontsize %i. Using 10." % fontsize + LOG.warn("Unsupported browser_fontsize %i. Using 10." % fontsize) fontsize = 11
fontdesc = pango.FontDescription("Courier bold %i" % fontsize) diff --git a/chirpui/reporting.py b/chirpui/reporting.py index 0f524c5..ad3c22a 100644 --- a/chirpui/reporting.py +++ b/chirpui/reporting.py @@ -50,12 +50,12 @@ except:
def should_report(): if not ENABLED: - LOG.debug("Not reporting due to recent failure") + LOG.info("Not reporting due to recent failure") return False
conf = config.get() if conf.get_bool("no_report"): - LOG.debug("Reporting disabled") + LOG.info("Reporting disabled") return False
return True @@ -65,7 +65,7 @@ def _report_model_usage(model, direction, success): global ENABLED if direction not in ["live", "download", "upload", "import", "export", "importsrc"]: - print "Invalid direction `%s'" % direction + LOG.warn("Invalid direction `%s'" % direction) return True # This is a bug, but not fatal
model = "%s_%s" % (model.VENDOR, model.MODEL) diff --git a/chirpui/settingsedit.py b/chirpui/settingsedit.py index 76264c9..e25727e 100644 --- a/chirpui/settingsedit.py +++ b/chirpui/settingsedit.py @@ -15,11 +15,14 @@
import gtk import gobject +import logging
from chirp import chirp_common from chirp import settings from chirpui import common, miscwidgets
+LOG = logging.getLogger(__name__) +
class RadioSettingProxy(settings.RadioSetting): def __init__(self, setting, editor): @@ -91,8 +94,8 @@ class SettingsEditor(common.Editor): elif isinstance(value, settings.RadioSettingValueString): value.set_value(widget.get_text()) else: - print "Unsupported widget type %s for %s" % \ - (element.value.__class__, element.get_name()) + LOG.error("Unsupported widget type %s for %s" % + (element.value.__class__, element.get_name()))
self._changed = True self._save_settings() @@ -181,7 +184,7 @@ class SettingsEditor(common.Editor): widget.set_text(str(value).rstrip()) widget.connect("changed", self._save_setting, value) else: - print "Unsupported widget type: %s" % value.__class__ + LOG.error("Unsupported widget type: %s" % value.__class__)
widget.set_sensitive(value.get_mutable()) widget.show() diff --git a/chirpui/shiftdialog.py b/chirpui/shiftdialog.py index e3f0454..e971611 100644 --- a/chirpui/shiftdialog.py +++ b/chirpui/shiftdialog.py @@ -17,9 +17,12 @@ import gtk import gobject import threading +import logging
from chirp import errors, chirp_common
+LOG = logging.getLogger(__name__) +
class ShiftDialog(gtk.Dialog): def __init__(self, rthread, parent=None): @@ -59,7 +62,7 @@ class ShiftDialog(gtk.Dialog): src = i.number dst = src + delta
- print "Moving %i to %i" % (src, dst) + LOG.info("Moving %i to %i" % (src, dst)) self.status(_("Moving {src} to {dst}").format(src=src, dst=dst), count / len(memories)) @@ -95,7 +98,7 @@ class ShiftDialog(gtk.Dialog): if pos > ulimit and not endokay: raise errors.InvalidMemoryLocation(_("No space to insert a row"))
- print "Found a hole: %i" % pos + LOG.debug("Found a hole: %i" % pos)
return mems
@@ -109,7 +112,7 @@ class ShiftDialog(gtk.Dialog): self.rthread.radio.erase_memory(start) return ret else: - print "No memory list?" + LOG.warn("No memory list?") return 0
def _delete_hole(self, start, all=False): @@ -119,7 +122,7 @@ class ShiftDialog(gtk.Dialog): self.rthread.radio.erase_memory(count+start) return count else: - print "No memory list?" + LOG.warn("No memory list?") return 0
def finished(self):
participants (1)
-
Zach Welch