Skip to content

Commit

Permalink
Merge pull request #268 from JoeLametta/python3
Browse files Browse the repository at this point in the history
Incremental code modernization for (future) Python 3 port
  • Loading branch information
JoeLametta authored Jun 8, 2018
2 parents 5db7656 + 241f44e commit 84fa7c0
Show file tree
Hide file tree
Showing 40 changed files with 407 additions and 417 deletions.
2 changes: 1 addition & 1 deletion whipper/command/accurip.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def do(self):

# now sort track results in checksum by highest confidence
sortedChecksums = []
for checksum, entries in checksums.items():
for checksum, entries in list(checksums.items()):
highest = max(d['confidence'] for d in entries)
sortedChecksums.append((highest, checksum))

Expand Down
8 changes: 4 additions & 4 deletions whipper/command/cd.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def do(self):
try:
self.program.result.cdparanoiaDefeatsCache = \
self.config.getDefeatsCache(*info)
except KeyError, e:
except KeyError as e:
logger.debug('Got key error: %r' % (e, ))
self.program.result.artist = self.program.metadata \
and self.program.metadata.artist \
Expand Down Expand Up @@ -219,7 +219,7 @@ class Rip(_CD):
# Requires opts.device

def add_arguments(self):
loggers = result.getLoggers().keys()
loggers = list(result.getLoggers())
default_offset = None
info = drive.getDeviceInfo(self.opts.device)
if info:
Expand Down Expand Up @@ -354,7 +354,7 @@ def _ripIfNotRipped(number):
logger.debug('ripIfNotRipped: path %r' % path)
trackResult.number = number

assert type(path) is unicode, "%r is not unicode" % path
assert isinstance(path, unicode), "%r is not unicode" % path
trackResult.filename = path
if number > 0:
trackResult.pregap = self.itable.tracks[number - 1].getPregap()
Expand Down Expand Up @@ -406,7 +406,7 @@ def _ripIfNotRipped(number):
len(self.itable.tracks),
extra))
break
except Exception, e:
except Exception as e:
logger.debug('Got exception %r on try %d',
e, tries)

Expand Down
18 changes: 9 additions & 9 deletions whipper/command/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,33 @@
def main():
try:
server = config.Config().get_musicbrainz_server()
except KeyError, e:
sys.stderr.write('whipper: %s\n' % e.message)
except KeyError as e:
sys.stderr.write('whipper: %s\n' % str(e))
sys.exit()

musicbrainzngs.set_hostname(server)
# register plugins with pkg_resources
distributions, _ = pkg_resources.working_set.find_plugins(
pkg_resources.Environment([directory.data_path('plugins')])
)
map(pkg_resources.working_set.add, distributions)
list(map(pkg_resources.working_set.add, distributions))
try:
cmd = Whipper(sys.argv[1:], os.path.basename(sys.argv[0]), None)
ret = cmd.do()
except SystemError, e:
except SystemError as e:
sys.stderr.write('whipper: error: %s\n' % e)
if (type(e) is common.EjectError and
if (isinstance(e, common.EjectError) and
cmd.options.eject in ('failure', 'always')):
eject_device(e.device)
return 255
except RuntimeError, e:
except RuntimeError as e:
print(e)
return 1
except KeyboardInterrupt:
return 2
except ImportError, e:
except ImportError as e:
raise
except task.TaskException, e:
except task.TaskException as e:
if isinstance(e.exception, ImportError):
raise ImportError(e.exception)
elif isinstance(e.exception, common.MissingDependencyException):
Expand Down Expand Up @@ -105,5 +105,5 @@ def handle_arguments(self):
self.parser.print_help()
sys.exit(0)
if self.options.version:
print "whipper %s" % whipper.__version__
print("whipper %s" % whipper.__version__)
sys.exit(0)
24 changes: 12 additions & 12 deletions whipper/command/mblookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,26 @@ def do(self):
try:
discId = unicode(self.options.mbdiscid)
except IndexError:
print 'Please specify a MusicBrainz disc id.'
print('Please specify a MusicBrainz disc id.')
return 3

metadatas = musicbrainz(discId)

print '%d releases' % len(metadatas)
print('%d releases' % len(metadatas))
for i, md in enumerate(metadatas):
print '- Release %d:' % (i + 1, )
print ' Artist: %s' % md.artist.encode('utf-8')
print ' Title: %s' % md.title.encode('utf-8')
print ' Type: %s' % md.releaseType.encode('utf-8') # noqa: E501
print ' URL: %s' % md.url
print ' Tracks: %d' % len(md.tracks)
print('- Release %d:' % (i + 1, ))
print(' Artist: %s' % md.artist.encode('utf-8'))
print(' Title: %s' % md.title.encode('utf-8'))
print(' Type: %s' % md.releaseType.encode('utf-8')) # noqa: E501
print(' URL: %s' % md.url)
print(' Tracks: %d' % len(md.tracks))
if md.catalogNumber:
print ' Cat no: %s' % md.catalogNumber
print(' Cat no: %s' % md.catalogNumber)
if md.barcode:
print ' Barcode: %s' % md.barcode
print(' Barcode: %s' % md.barcode)

for j, track in enumerate(md.tracks):
print ' Track %2d: %s - %s' % (
print(' Track %2d: %s - %s' % (
j + 1, track.artist.encode('utf-8'),
track.title.encode('utf-8')
)
))
6 changes: 3 additions & 3 deletions whipper/command/offset.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def handle_arguments(self):
for b in blocks:
if ':' in b:
a, b = b.split(':')
self._offsets.extend(range(int(a), int(b) + 1))
self._offsets.extend(list(range(int(a), int(b) + 1)))
else:
self._offsets.append(int(b))

Expand Down Expand Up @@ -117,7 +117,7 @@ def match(archecksums, track, responses):
sys.stdout.write('Trying read offset %d ...\n' % offset)
try:
archecksums = self._arcs(runner, table, 1, offset)
except task.TaskException, e:
except task.TaskException as e:

# let MissingDependency fall through
if isinstance(e.exception,
Expand Down Expand Up @@ -150,7 +150,7 @@ def match(archecksums, track, responses):
for track in range(2, (len(table.tracks) + 1) - 1):
try:
archecksums = self._arcs(runner, table, track, offset)
except task.TaskException, e:
except task.TaskException as e:
if isinstance(e.exception, cdparanoia.FileSizeError):
sys.stdout.write(
'WARNING: cannot rip with offset %d...\n' %
Expand Down
8 changes: 4 additions & 4 deletions whipper/common/accurip.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def _save_entry(raw_entry, path):
# XXX: os.makedirs(exist_ok=True) in py3
try:
makedirs(dirname(path))
except OSError, e:
except OSError as e:
if e.errno != EEXIST:
logger.error('could not save entry to %s: %r' % (path, str(e)))
return
Expand Down Expand Up @@ -231,7 +231,7 @@ def verify_result(result, responses, checksums):
# exclude HTOA from AccurateRip verification
# NOTE: if pre-gap hidden audio support is expanded to include
# tracks other than HTOA, this is invalid.
tracks = filter(lambda t: t.number != 0, result.tracks)
tracks = [t for t in result.tracks if t.number != 0]
if not tracks:
return False
_assign_checksums_and_confidences(tracks, checksums, responses)
Expand All @@ -251,10 +251,10 @@ def print_report(result):
conf = '(max confidence %3d)' % track.AR['DBMaxConfidence']
if track.AR['v1']['DBCRC'] or track.AR['v2']['DBCRC']:
status = 'rip accurate'
db = ', '.join(filter(None, (
db = ', '.join([_f for _f in (
track.AR['v1']['DBCRC'],
track.AR['v2']['DBCRC']
)))
) if _f])
max_conf = max(
[track.AR[v]['DBConfidence'] for v in ('v1', 'v2')]
)
Expand Down
2 changes: 1 addition & 1 deletion whipper/common/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def __init__(self, path):
self.path = path
try:
os.makedirs(self.path)
except OSError, e:
except OSError as e:
if e.errno != 17: # FIXME
raise

Expand Down
4 changes: 2 additions & 2 deletions whipper/common/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def getRealPath(refPath, filePath):
@type filePath: unicode
"""
assert type(filePath) is unicode, "%r is not unicode" % filePath
assert isinstance(filePath, unicode), "%r is not unicode" % filePath

if os.path.exists(filePath):
return filePath
Expand Down Expand Up @@ -298,7 +298,7 @@ def get(self):
vre = self._regexp.search(output)
if vre:
version = self._expander % vre.groupdict()
except OSError, e:
except OSError as e:
import errno
if e.errno == errno.ENOENT:
raise MissingDependencyException(self._dep)
Expand Down
2 changes: 1 addition & 1 deletion whipper/common/drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@


def _listify(listOrString):
if type(listOrString) == str:
if isinstance(listOrString, str):
return [listOrString, ]

return listOrString
Expand Down
2 changes: 1 addition & 1 deletion whipper/common/encode.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def start(self, runner):
def _tag(self):
w = FLAC(self.track_path)

for k, v in self.tags.items():
for k, v in list(self.tags.items()):
w[k] = v

w.save()
Expand Down
2 changes: 1 addition & 1 deletion whipper/common/mbngs.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def musicbrainz(discid, country=None, record=False):
try:
result = musicbrainzngs.get_releases_by_discid(
discid, includes=["artists", "recordings", "release-groups"])
except musicbrainzngs.ResponseError, e:
except musicbrainzngs.ResponseError as e:
if isinstance(e.cause, urllib2.HTTPError):
if e.cause.code == 404:
raise NotFoundException(e)
Expand Down
30 changes: 15 additions & 15 deletions whipper/common/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ def __init__(self, config, record=False, stdout=sys.stdout):

d = {}

for key, default in {
for key, default in list({
'fat': True,
'special': False
}.items():
}.items()):
value = None
value = self._config.getboolean('main', 'path_filter_' + key)
if value is None:
Expand Down Expand Up @@ -115,7 +115,7 @@ def getTable(self, runner, cddbdiscid, mbdiscid, device, offset):
tdict = {}

# Ignore old cache, since we do not know what offset it used.
if type(ptable.object) is dict:
if isinstance(ptable.object, dict):
tdict = ptable.object

if offset in tdict:
Expand Down Expand Up @@ -193,8 +193,8 @@ def getPath(self, outdir, template, mbdiscid, metadata, track_number=None):
- %x: audio extension, lowercase
- %X: audio extension, uppercase
"""
assert type(outdir) is unicode, "%r is not unicode" % outdir
assert type(template) is unicode, "%r is not unicode" % template
assert isinstance(outdir, unicode), "%r is not unicode" % outdir
assert isinstance(template, unicode), "%r is not unicode" % template
v = {}
v['A'] = 'Unknown Artist'
v['d'] = mbdiscid # fallback for title
Expand Down Expand Up @@ -252,7 +252,7 @@ def getCDDB(self, cddbdiscid):
if code == 200:
return md['title']

except IOError, e:
except IOError as e:
# FIXME: for some reason errno is a str ?
if e.errno == 'socket error':
self._stdout.write("Warning: network error: %r\n" % (e, ))
Expand Down Expand Up @@ -283,13 +283,13 @@ def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None,
country=country,
record=self._record)
break
except mbngs.NotFoundException, e:
except mbngs.NotFoundException as e:
logger.warning("release not found: %r" % (e, ))
break
except musicbrainzngs.NetworkError, e:
except musicbrainzngs.NetworkError as e:
logger.warning("network error: %r" % (e, ))
break
except mbngs.MusicBrainzException, e:
except mbngs.MusicBrainzException as e:
logger.warning("musicbrainz exception: %r" % (e, ))
time.sleep(5)
continue
Expand Down Expand Up @@ -329,7 +329,7 @@ def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None,

if not release and len(metadatas) > 1:
# Select the release that most closely matches the duration.
lowest = min(deltas.keys())
lowest = min(list(deltas))

if prompt:
guess = (deltas[lowest])[0].mbid
Expand Down Expand Up @@ -375,7 +375,7 @@ def getMusicBrainz(self, ittoc, mbdiscid, release=None, country=None,
releaseTitle, i,
metadata.releaseTitle))

if (not release and len(deltas.keys()) > 1):
if (not release and len(list(deltas)) > 1):
self._stdout.write('\n')
self._stdout.write('Picked closest match in duration.\n')
self._stdout.write('Others may be wrong in MusicBrainz, '
Expand Down Expand Up @@ -424,8 +424,8 @@ def getTagList(self, number):
title = track.title
mbidTrack = track.mbid
mbidTrackArtist = track.mbidArtist
except IndexError, e:
print 'ERROR: no track %d found, %r' % (number, e)
except IndexError as e:
print('ERROR: no track %d found, %r' % (number, e))
raise
else:
# htoa defaults to disc's artist
Expand Down Expand Up @@ -478,7 +478,7 @@ def verifyTrack(self, runner, trackResult):

try:
runner.run(t)
except task.TaskException, e:
except task.TaskException as e:
if isinstance(e.exception, common.MissingFrames):
logger.warning('missing frames for %r' % trackResult.filename)
return False
Expand Down Expand Up @@ -565,7 +565,7 @@ def verifyImage(self, runner, table):

checksums = accurip.calculate_checksums([
os.path.join(os.path.dirname(self.cuePath), t.indexes[1].path)
for t in filter(lambda t: t.number != 0, cueImage.cue.table.tracks)
for t in [t for t in cueImage.cue.table.tracks if t.number != 0]
])
if not (checksums and any(checksums['v1']) and any(checksums['v2'])):
return False
Expand Down
4 changes: 2 additions & 2 deletions whipper/common/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def start(self, runner):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True, cwd=self.cwd)
except OSError, e:
except OSError as e:
import errno
if e.errno == errno.ENOENT:
self.commandMissing()
Expand Down Expand Up @@ -88,7 +88,7 @@ def _read(self, runner):
return

self._done()
except Exception, e:
except Exception as e:
logger.debug('exception during _read(): %r', str(e))
self.setException(e)
self.stop()
Expand Down
Loading

0 comments on commit 84fa7c0

Please sign in to comment.