Replace sys.std{out,err} statements with logger/print calls (#331)

* Change global default log level to 'INFO'

We're going to increase our usage of logger statements instead of print instructions (where deemed opportune).

* Replace sys.std{out,err} statements with logger/print calls

Fixes #303.
This commit is contained in:
JoeLametta
2018-12-13 20:21:26 +00:00
committed by GitHub
parent 32cd902821
commit c377417108
9 changed files with 139 additions and 193 deletions

View File

@@ -18,8 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with whipper. If not, see <http://www.gnu.org/licenses/>.
import sys
from whipper.command.basecommand import BaseCommand
from whipper.common.accurip import get_db_entry, ACCURATERIP_URL
@@ -42,18 +40,17 @@ retrieves and display accuraterip data from the given URL
count = responses[0].num_tracks
sys.stdout.write("Found %d responses for %d tracks\n\n" % (
len(responses), count))
logger.info("Found %d responses for %d tracks",
(len(responses), count))
for (i, r) in enumerate(responses):
if r.num_tracks != count:
sys.stdout.write(
"Warning: response %d has %d tracks instead of %d\n" % (
i, r.num_tracks, count))
logger.warning("response %d has %d tracks instead of %d", (
i, r.num_tracks, count))
# checksum and confidence by track
for track in range(count):
sys.stdout.write("Track %d:\n" % (track + 1))
print("Track %d:" % (track + 1))
checksums = {}
for (i, r) in enumerate(responses):
@@ -82,9 +79,9 @@ retrieves and display accuraterip data from the given URL
sortedChecksums.reverse()
for highest, checksum in sortedChecksums:
sys.stdout.write(" %d result(s) for checksum %s: %s\n" % (
len(checksums[checksum]), checksum,
str(checksums[checksum])))
print(" %d result(s) for checksum %s: %s" % (
len(checksums[checksum]),
checksum, str(checksums[checksum])))
class AccuRip(BaseCommand):

View File

@@ -22,7 +22,6 @@ import argparse
import cdio
import os
import glob
import sys
import logging
from whipper.command.basecommand import BaseCommand
from whipper.common import (
@@ -84,29 +83,28 @@ class _CD(BaseCommand):
def do(self):
self.config = config.Config()
self.program = program.Program(self.config,
record=self.options.record,
stdout=sys.stdout)
record=self.options.record)
self.runner = task.SyncRunner()
# if the device is mounted (data session), unmount it
self.device = self.options.device
sys.stdout.write('Checking device %s\n' % self.device)
logger.info('checking device %s', self.device)
utils.load_device(self.device)
utils.unmount_device(self.device)
# first, read the normal TOC, which is fast
print("Reading TOC...")
logger.info("reading TOC...")
self.ittoc = self.program.getFastToc(self.runner, self.device)
# already show us some info based on this
self.program.getRipResult(self.ittoc.getCDDBDiscId())
sys.stdout.write("CDDB disc id: %s\n" % self.ittoc.getCDDBDiscId())
print("CDDB disc id: %s" % self.ittoc.getCDDBDiscId())
self.mbdiscid = self.ittoc.getMusicBrainzDiscId()
sys.stdout.write("MusicBrainz disc id %s\n" % self.mbdiscid)
print("MusicBrainz disc id %s" % self.mbdiscid)
sys.stdout.write("MusicBrainz lookup URL %s\n" %
self.ittoc.getMusicBrainzSubmitURL())
print("MusicBrainz lookup URL %s" %
self.ittoc.getMusicBrainzSubmitURL())
self.program.metadata = (
self.program.getMusicBrainz(self.ittoc, self.mbdiscid,
@@ -120,12 +118,12 @@ class _CD(BaseCommand):
cddbid = self.ittoc.getCDDBValues()
cddbmd = self.program.getCDDB(cddbid)
if cddbmd:
sys.stdout.write('FreeDB identifies disc as %s\n' % cddbmd)
logger.info('FreeDB identifies disc as %s', cddbmd)
# also used by rip cd info
if not getattr(self.options, 'unknown', False):
logger.critical("unable to retrieve disc metadata, "
"--unknown not passed")
"--unknown argument not passed")
return -1
self.program.result.isCdr = cdrdao.DetectCdr(self.device)
@@ -236,8 +234,7 @@ Log files will log the path to tracks relative to this directory.
if info:
try:
default_offset = config.Config().getReadOffset(*info)
sys.stdout.write("Using configured read offset %d\n" %
default_offset)
logger.info("using configured read offset %d", default_offset)
except KeyError:
pass
@@ -340,7 +337,8 @@ Log files will log the path to tracks relative to this directory.
logger.critical(msg)
raise RuntimeError(msg)
else:
print("creating output directory %s" % dirname.encode('utf-8'))
logger.info("creating output directory %s",
dirname.encode('utf-8'))
os.makedirs(dirname)
# FIXME: turn this into a method
@@ -381,11 +379,11 @@ Log files will log the path to tracks relative to this directory.
logger.debug('previous result %r, expected %r' % (
trackResult.filename, path))
sys.stdout.write('Verifying track %d of %d: %s\n' % (
number, len(self.itable.tracks),
os.path.basename(path).encode('utf-8')))
logger.info('verifying track %d of %d: %s', (
number, len(self.itable.tracks),
os.path.basename(path).encode('utf-8')))
if not self.program.verifyTrack(self.runner, trackResult):
sys.stdout.write('Verification failed, reripping...\n')
logger.warning('verification failed, reripping...')
os.unlink(path)
if not os.path.exists(path):
@@ -399,9 +397,9 @@ Log files will log the path to tracks relative to this directory.
tries += 1
if tries > 1:
extra = " (try %d)" % tries
sys.stdout.write('Ripping track %d of %d%s: %s\n' % (
number, len(self.itable.tracks), extra,
os.path.basename(path).encode('utf-8')))
logger.info('ripping track %d of %d%s: %s', (
number, len(self.itable.tracks), extra,
os.path.basename(path).encode('utf-8')))
try:
logger.debug('ripIfNotRipped: track %d, try %d',
number, tries)
@@ -427,17 +425,14 @@ Log files will log the path to tracks relative to this directory.
"track can't be ripped. "
"Rip attempts number is equal to 'MAX_TRIES'")
if trackResult.testcrc == trackResult.copycrc:
sys.stdout.write('CRCs match for track %d\n' % number)
logger.info('CRCs match for track %d', number)
else:
raise RuntimeError(
"CRCs did not match for track %d\n" % number
"CRCs did not match for track %d" % number
)
sys.stdout.write(
'Peak level: {}\n'.format(trackResult.peak))
sys.stdout.write(
'Rip quality: {:.2%}\n'.format(trackResult.quality))
print('Peak level: %.6f' % (trackResult.peak / 32768.0))
print('Rip quality: {:.2%}'.format(trackResult.quality))
# overlay this rip onto the Table
if number == 0:
@@ -452,8 +447,7 @@ Log files will log the path to tracks relative to this directory.
logger.debug('Unlinking %r', trackResult.filename)
os.unlink(trackResult.filename)
trackResult.filename = None
sys.stdout.write(
'HTOA discarded, contains digital silence\n')
logger.info('HTOA discarded, contains digital silence')
else:
self.itable.setFile(1, 0, trackResult.filename,
self.ittoc.getTrackStart(1), number)
@@ -467,14 +461,15 @@ Log files will log the path to tracks relative to this directory.
htoa = self.program.getHTOA()
if htoa:
start, stop = htoa
print('found Hidden Track One Audio from frame %d to %d' % (
start, stop))
logger.info('found Hidden Track One Audio from frame %d to %d', (
start, stop))
_ripIfNotRipped(0)
for i, track in enumerate(self.itable.tracks):
# FIXME: rip data tracks differently
if not track.audio:
print('skipping data track %d, not implemented' % (i + 1))
logger.warning('skipping data track %d, not implemented',
(i + 1))
# FIXME: make it work for now
track.indexes[1].relative = 0
continue
@@ -489,7 +484,7 @@ Log files will log the path to tracks relative to this directory.
try:
self.program.verifyImage(self.runner, self.ittoc)
except accurip.EntryNotFound:
print('AccurateRip entry not found')
logger.warning('AccurateRip entry not found')
accurip.print_report(self.program.result)

View File

@@ -18,8 +18,6 @@
# You should have received a copy of the GNU General Public License
# along with whipper. If not, see <http://www.gnu.org/licenses/>.
import sys
from whipper.command.basecommand import BaseCommand
from whipper.common import config, drive
from whipper.extern.task import task
@@ -40,24 +38,21 @@ class Analyze(BaseCommand):
runner.run(t)
if t.defeatsCache is None:
sys.stdout.write(
'Cannot analyze the drive. Is there a CD in it?\n')
logger.critical('cannot analyze the drive: is there a CD in it?')
return
if not t.defeatsCache:
sys.stdout.write(
'cdparanoia cannot defeat the audio cache on this drive.\n')
logger.info('cdparanoia cannot defeat the audio cache '
'on this drive')
else:
sys.stdout.write(
'cdparanoia can defeat the audio cache on this drive.\n')
logger.info('cdparanoia can defeat the audio cache on this drive')
info = drive.getDeviceInfo(self.options.device)
if not info:
sys.stdout.write('Drive caching behaviour not saved:'
'could not get device info (requires pycdio).\n')
logger.error('Drive caching behaviour not saved: '
'could not get device info')
return
sys.stdout.write(
'Adding drive cache behaviour to configuration file.\n')
logger.info('adding drive cache behaviour to configuration file')
config.Config().setDefeatsCache(
info[0], info[1], info[2], t.defeatsCache)
@@ -72,48 +67,38 @@ class List(BaseCommand):
self.config = config.Config()
if not paths:
sys.stdout.write('No drives found.\n')
sys.stdout.write('Create /dev/cdrom if you have a CD drive, \n')
sys.stdout.write('or install pycdio for better detection.\n')
logger.critical('No drives found. Create /dev/cdrom '
'if you have a CD drive, or install '
'pycdio for better detection')
return
try:
import cdio as _ # noqa: F401 (TODO: fix it in a separate PR?)
except ImportError:
sys.stdout.write(
'Install pycdio for vendor/model/release detection.\n')
logger.error('install pycdio for vendor/model/release detection')
return
for path in paths:
vendor, model, release = drive.getDeviceInfo(path)
sys.stdout.write(
"drive: %s, vendor: %s, model: %s, release: %s\n" % (
path, vendor, model, release))
print("drive: %s, vendor: %s, model: %s, release: %s" % (
path, vendor, model, release))
try:
offset = self.config.getReadOffset(
vendor, model, release)
sys.stdout.write(
" Configured read offset: %d\n" % offset)
print(" Configured read offset: %d" % offset)
except KeyError:
# Note spaces at the beginning for pretty terminal output
sys.stdout.write(" "
"No read offset found. "
"Run 'whipper offset find'\n")
logger.warning("no read offset found. "
"Run 'whipper offset find'")
try:
defeats = self.config.getDefeatsCache(
vendor, model, release)
sys.stdout.write(
" Can defeat audio cache: %s\n" % defeats)
print(" Can defeat audio cache: %s" % defeats)
except KeyError:
sys.stdout.write(
" Unknown whether audio cache can be defeated. "
"Run 'whipper drive analyze'\n")
if not paths:
sys.stdout.write('No drives found.\n')
logger.warning("unknown whether audio cache can be "
"defeated. Run 'whipper drive analyze'")
class Drive(BaseCommand):

View File

@@ -19,12 +19,7 @@ logger = logging.getLogger(__name__)
def main():
try:
server = config.Config().get_musicbrainz_server()
except KeyError as e:
sys.stderr.write('whipper: %s\n' % str(e))
sys.exit()
server = config.Config().get_musicbrainz_server()
musicbrainzngs.set_hostname(server)
# register plugins with pkg_resources
distributions, _ = pkg_resources.working_set.find_plugins(
@@ -35,7 +30,7 @@ def main():
cmd = Whipper(sys.argv[1:], os.path.basename(sys.argv[0]), None)
ret = cmd.do()
except SystemError as e:
sys.stderr.write('whipper: error: %s\n' % e)
logger.critical("SystemError: %s", e)
if (isinstance(e, common.EjectError) and
cmd.options.eject in ('failure', 'always')):
eject_device(e.device)
@@ -51,18 +46,17 @@ def main():
if isinstance(e.exception, ImportError):
raise ImportError(e.exception)
elif isinstance(e.exception, common.MissingDependencyException):
sys.stderr.write('whipper: error: missing dependency "%s"\n' %
e.exception.dependency)
logger.critical('missing dependency "%s"', e.exception.dependency)
return 255
if isinstance(e.exception, common.EmptyError):
logger.debug("EmptyError: %r", str(e.exception))
sys.stderr.write('whipper: error: Could not create encoded file.\n') # noqa: E501
logger.critical('could not create encoded file')
return 255
# in python3 we can instead do `raise e.exception` as that would show
# the exception's original context
sys.stderr.write(e.exceptionMessage)
logger.critical(e.exceptionMessage)
return 255
return ret if ret else 0

View File

@@ -20,7 +20,6 @@
import argparse
import os
import sys
import tempfile
import logging
from whipper.command.basecommand import BaseCommand
@@ -79,7 +78,7 @@ CD in the AccurateRip database."""
device = self.options.device
# if necessary, load and unmount
sys.stdout.write('Checking device %s\n' % device)
logger.info('checking device %s', device)
utils.load_device(device)
utils.unmount_device(device)
@@ -116,25 +115,22 @@ CD in the AccurateRip database."""
return None, None
for offset in self._offsets:
sys.stdout.write('Trying read offset %d ...\n' % offset)
logger.info('trying read offset %d...', offset)
try:
archecksums = self._arcs(runner, table, 1, offset)
except task.TaskException as e:
# let MissingDependency fall through
if isinstance(e.exception,
common.MissingDependencyException):
if isinstance(e.exception, common.MissingDependencyException):
raise e
if isinstance(e.exception, cdparanoia.FileSizeError):
sys.stdout.write(
'WARNING: cannot rip with offset %d...\n' % offset)
logger.warning('cannot rip with offset %d...' % offset)
continue
logger.warning("Unknown task exception for offset %d: %r" % (
logger.warning("unknown task exception for offset %d: %r" % (
offset, e))
sys.stdout.write(
'WARNING: cannot rip with offset %d...\n' % offset)
logger.warning('cannot rip with offset %d...' % offset)
continue
logger.debug('AR checksums calculated: %s %s' % archecksums)
@@ -142,10 +138,9 @@ CD in the AccurateRip database."""
c, i = match(archecksums, 1, responses)
if c:
count = 1
logger.debug('MATCHED against response %d' % i)
sys.stdout.write(
'Offset of device is likely %d, confirming ...\n' %
offset)
logger.debug('matched against response %d' % i)
logger.info('offset of device is likely %d, confirming...',
offset)
# now try and rip all other tracks as well, except for the
# last one (to avoid readers that can't do overread
@@ -154,9 +149,8 @@ CD in the AccurateRip database."""
archecksums = self._arcs(runner, table, track, offset)
except task.TaskException as e:
if isinstance(e.exception, cdparanoia.FileSizeError):
sys.stdout.write(
'WARNING: cannot rip with offset %d...\n' %
offset)
logger.warning('cannot rip with offset %d...' %
offset)
continue
c, i = match(archecksums, track, responses)
@@ -169,16 +163,16 @@ CD in the AccurateRip database."""
self._foundOffset(device, offset)
return 0
else:
sys.stdout.write(
'Only %d of %d tracks matched, continuing ...\n' % (
count, len(table.tracks)))
logger.warning('only %d of %d tracks matched, '
'continuing...',
(count, len(table.tracks)))
sys.stdout.write('No matching offset found.\n')
sys.stdout.write('Consider trying again with a different disc.\n')
logger.error('no matching offset found. '
'Consider trying again with a different disc')
def _arcs(self, runner, table, track, offset):
# rips the track with the given offset, return the arcs checksums
logger.debug('Ripping track %r with offset %d ...', track, offset)
logger.debug('ripping track %r with offset %d...', track, offset)
fd, path = tempfile.mkstemp(
suffix=u'.track%02d.offset%d.whipper.wav' % (
@@ -205,17 +199,15 @@ CD in the AccurateRip database."""
return ("%08x" % v1, "%08x" % v2)
def _foundOffset(self, device, offset):
sys.stdout.write('\nRead offset of device is: %d.\n' %
offset)
print('\nRead offset of device is: %d.' % offset)
info = drive.getDeviceInfo(device)
if not info:
sys.stdout.write(
'Offset not saved: could not get '
'device info (requires pycdio).\n')
logger.error('offset not saved: '
'could not get device info (requires pycdio)')
return
sys.stdout.write('Adding read offset to configuration file.\n')
logger.info('adding read offset to configuration file')
config.Config().setReadOffset(info[0], info[1], info[2],
offset)