Skip to content

Commit

Permalink
preparation for Python 3
Browse files Browse the repository at this point in the history
  • Loading branch information
albertz committed Jun 10, 2016
1 parent 757f437 commit 54549a8
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 35 deletions.
12 changes: 6 additions & 6 deletions src/ModuleSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ def threadMain(self):
while True:
if self.module:
try:
reload(self.module)
reload_module(self.module)
except Exception:
print "couldn't reload module", self.module
print("couldn't reload module", self.module)
sys.excepthook(*sys.exc_info())
# continue anyway, maybe it still works and maybe the mainFunc does sth good/important
else:
Expand All @@ -46,7 +46,7 @@ def threadMain(self):
except KeyboardInterrupt:
break
except Exception:
print "Exception in module", self.name
print("Exception in module", self.name)
sys.excepthook(*sys.exc_info())
if not thread.reload: break
sys.stdout.write("reloading module %s\n" % self.name)
Expand Down Expand Up @@ -112,10 +112,10 @@ def scanModules():
def reloadModules():
# reload some custom random Python modules
import utils
reload(utils)
reload_module(utils)
import Song, State
reload(Song)
reload(State)
reload_module(Song)
reload_module(State)
# reload all our modules
for m in modules:
m.reload()
Expand Down
20 changes: 10 additions & 10 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
if not getattr(sys, "MusicPlayerBin", None):
faulthandler.enable(all_threads=True)
except ImportError:
print "note: faulthandler module not available"
print("note: faulthandler module not available")
faulthandler = None

# Do this early to do some option parsing and maybe special handling.
Expand Down Expand Up @@ -66,8 +66,8 @@ def main():
if appinfo.args.forkExecProc:
# Only import utils now for this case.
# Otherwise, I want "--pyshell" to be without utils loaded.
import utils
utils.ExecingProcess.checkExec()
import TaskSystem
TaskSystem.ExecingProcess.checkExec()

# Early check for "--pyshell".
# This is a simple debug shell where we don't load anything.
Expand All @@ -85,8 +85,8 @@ def main():
import utils
import time

print "MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform
print "startup on", utils.formatDate(time.time())
print("MusicPlayer", appinfo.version, "from", appinfo.buildTime, "git-ref", appinfo.gitRef[:10], "on", appinfo.platform, "(%s)" % sys.platform)
print("startup on", utils.formatDate(time.time()))

utils.setCurThreadName("Python main")

Expand All @@ -109,7 +109,7 @@ def main():
import objc
except Exception:
if sys.platform == "darwin":
print "Error while importing objc"
print("Error while importing objc")
sys.excepthook(*sys.exc_info())
# Otherwise it doesn't matter.
try:
Expand All @@ -121,16 +121,16 @@ def main():
import AppKit
except Exception:
# Print error in any case, also ImportError, because we would expect that this works.
print "Error while importing AppKit"
print("Error while importing AppKit")
sys.excepthook(*sys.exc_info())

# Import core module here. This is mostly as an early error check.
try:
import musicplayer
except Exception:
print "Error while importing core module! This is fatal."
print("Error while importing core module! This is fatal.")
sys.excepthook(*sys.exc_info())
print "Environment:"
print("Environment:")
pprint(os.environ)
raise

Expand Down Expand Up @@ -187,7 +187,7 @@ def main():

while True:
try: stdinconsole.readNextInput() # wait for KeyboardInterrupt
except BaseException, e:
except BaseException as e:
State.state.updates.put((e, (), {}))
State.state.updates.cancelAll()
break
Expand Down
22 changes: 12 additions & 10 deletions src/modules/songdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from Song import Song
import appinfo
import utils
from utils import to_bytes, unicode
import TaskSystem
from utils import safe_property

Expand Down Expand Up @@ -261,7 +262,7 @@ def Reset(clazz):
except Exception as exc:
# Maybe we had an old LevelDB or some other corruption.
# Not much we can do for recovering...
print "DB %s opening error %r, I will reset the DB, sorry..." % (self.filename, exc)
print("DB %s opening error %r, I will reset the DB, sorry..." % (self.filename, exc))
self._removeOldDb()
self._initNew()

Expand Down Expand Up @@ -346,7 +347,7 @@ def __getitem__(self, key):
except KeyError: pass
origKey = key
key = dbRepr(key)
key = buffer(key)
key = to_bytes(key)
with self.readlock:
cur = self._selectCmd("select value from data where key=? limit 1", (key,))
values = cur.fetchall()
Expand All @@ -364,9 +365,9 @@ def __getitem__(self, key):
def __setitem__(self, key, value):
self.cache[key] = value
key = dbRepr(key)
key = buffer(key)
key = to_bytes(key)
value = dbRepr(value)
value = buffer(value)
value = to_bytes(value)
self._actionCmd("replace into data values (?,?)", (key, value))

def setdefault(self, key, value):
Expand Down Expand Up @@ -482,7 +483,7 @@ def hash(s):
HashFileBufferSize = 1024 * 10

def hashFile(f):
if isinstance(f, (str,unicode)): f = open(f)
if isinstance(f, (str, unicode)): f = open(f)
import hashlib
h = hashlib.sha1()
while True:
Expand Down Expand Up @@ -601,7 +602,7 @@ def _dbDict(self):

def __getattr__(self, attr):
try: return self._dbDict[attr]
except KeyError: raise AttributeError, "no attrib " + attr
except KeyError: raise AttributeError("no attrib " + attr)

def update(self, attr, updateFunc, default=None):
global songDb
Expand Down Expand Up @@ -658,7 +659,7 @@ def _dbDict(self):

def __getattr__(self, attr):
try: return self._dbDict[attr]
except KeyError: raise AttributeError, "no attrib " + attr
except KeyError: raise AttributeError("no attrib " + attr)

def update(self, attr, updateFunc, default=None):
global songDb
Expand Down Expand Up @@ -1023,7 +1024,8 @@ def addTokenList(tokenList):
"create_command": "CREATE TABLE %s(rowid INTEGER PRIMARY KEY, songid BLOB UNIQUE)" }

def insertSearchEntry_raw(songId, tokens):
songId = buffer(songId)
songId = to_bytes(songId)
global songSearchIndexRefDb
with songSearchIndexRefDb.writelock:
rowId = songSearchIndexRefDb._selectCmd("select rowid from data where songid=?", (songId,)).fetchone()
if rowId is not None:
Expand Down Expand Up @@ -1084,11 +1086,11 @@ def dumpDatabases():
global songDb, songHashDb
import sys
from pprint import pprint
print "Main DB:"
print("Main DB:")
for key,value in songDb.rangeIter():
sys.stdout.write("%r: \n" % key)
pprint(value, indent=2)
print "\nHashes:"
print("\nHashes:")
for key,value in songHashDb.rangeIter():
sys.stdout.write("%r: " % key)
pprint(value, indent=2)
Expand Down
44 changes: 35 additions & 9 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,32 @@
from collections import deque
import time
import better_exchook
import types


if sys.version_info[0] >= 3:
NumberTypes = (int, float)
unicode = str
py2_str = bytes

def to_bytes(s):
if isinstance(s, str): return s.encode("utf8")
assert isinstance(s, bytes)
return s

from importlib import reload as reload_module

else: # Python <= 2
NumberTypes = (types.IntType, types.LongType, types.FloatType)
py2_unicode = unicode
unicode = py2_unicode
py2_str = str

def to_bytes(s):
return buffer(s)

reload_module = reload


# some global variable which indicates that we are quitting just right now
quit = False
Expand Down Expand Up @@ -78,21 +104,21 @@ def __getattr__(self, attr):
# forward prop.setter, prop.deleter, etc.
return getattr(self.prop, attr)


def formatDate(t):
import types
if isinstance(t, (types.IntType,types.LongType,types.FloatType)):
if isinstance(t, NumberTypes):
t = time.gmtime(t)
return time.strftime("%Y-%m-%d %H:%M:%S +0000", t)

def formatTime(t):
if t is None: return "?"
t = round(t)
mins = long(t // 60)
mins = int(t // 60)
t -= mins * 60
hours = mins // 60
mins -= hours * 60
if hours: return "%02i:%02i:%02.0f" % (hours,mins,t)
return "%02i:%02.0f" % (mins,t)
if hours: return "%02i:%02i:%02.0f" % (hours, mins, t)
return "%02i:%02.0f" % (mins, t)

def formatFilesize(s):
L = 800
Expand All @@ -116,7 +142,7 @@ def betterRepr(o):
if isinstance(o, tuple):
return "(" + ", ".join(map(betterRepr, o)) + ")"
if isinstance(o, dict):
return "{\n" + "".join(map(lambda (k,v): betterRepr(k) + ": " + betterRepr(v) + ",\n", sorted(o.iteritems()))) + "}"
return "{\n" + "".join(map(lambda k, v: betterRepr(k) + ": " + betterRepr(v) + ",\n", sorted(o.items()))) + "}"
# fallback
return repr(o)

Expand Down Expand Up @@ -509,7 +535,7 @@ def killMeHard():
def dumpAllThreads():
import sys
if not hasattr(sys, "_current_frames"):
print "Warning: dumpAllThreads: no sys._current_frames"
print("Warning: dumpAllThreads: no sys._current_frames")
return

import threading
Expand All @@ -521,7 +547,7 @@ def dumpAllThreads():
def dumpThread(threadId):
import sys
if not hasattr(sys, "_current_frames"):
print "Warning: dumpThread: no sys._current_frames"
print("Warning: dumpThread: no sys._current_frames")
return

if threadId not in sys._current_frames():
Expand Down Expand Up @@ -679,7 +705,7 @@ def setCurThreadName(name):
_pthread_setname_np.restype = ctypes.c_int

except ImportError:
print "setCurThreadName: failed to import libpthread"
print("setCurThreadName: failed to import libpthread")

if _pthread_setname_np is None: return

Expand Down

0 comments on commit 54549a8

Please sign in to comment.