From 54fa31ba1793e5bc6bea012c44904e443d20a24e Mon Sep 17 00:00:00 2001 From: rdb Date: Fri, 25 Mar 2016 17:06:50 +0100 Subject: [PATCH] StandardError -> Exception, other 2to3 changes, threaded 2to3 --- direct/src/actor/Actor.py | 2 +- direct/src/directdevices/DirectRadamec.py | 2 +- direct/src/directnotify/Notifier.py | 2 +- direct/src/directscripts/gendocs.py | 30 ++++++----- .../src/distributed/ConnectionRepository.py | 2 +- direct/src/distributed/ServerRepository.py | 2 +- .../extension_native_helpers.py | 6 ++- direct/src/fsm/FSM.py | 8 +-- direct/src/fsm/State.py | 12 ++--- direct/src/gui/DirectGuiBase.py | 19 ++++--- direct/src/gui/DirectScrollBar.py | 2 +- direct/src/gui/DirectSlider.py | 2 +- direct/src/interval/FunctionInterval.py | 6 +-- direct/src/interval/ProjectileInterval.py | 2 +- direct/src/p3d/AppRunner.py | 18 +++---- direct/src/p3d/JavaScript.py | 16 ++++-- direct/src/p3d/PackageInstaller.py | 2 +- direct/src/p3d/PackageMerger.py | 8 +-- direct/src/p3d/Packager.py | 52 +++++++++---------- direct/src/p3d/PatchMaker.py | 4 +- direct/src/p3d/SeqValue.py | 2 +- direct/src/p3d/packp3d.py | 12 ++--- direct/src/p3d/runp3d.py | 2 +- direct/src/plugin_npapi/make_osx_bundle.py | 4 +- .../src/plugin_standalone/make_osx_bundle.py | 4 +- direct/src/showbase/Audio3DManager.py | 4 +- direct/src/showbase/Loader.py | 2 +- direct/src/showbase/Messenger.py | 12 ++--- direct/src/showbase/PythonUtil.py | 18 +++---- direct/src/showbase/RandomNumGen.py | 14 ++--- direct/src/showbase/ShowBase.py | 8 +-- direct/src/showutil/FreezeTool.py | 18 ++++--- direct/src/stdpy/glob.py | 2 +- direct/src/stdpy/thread.py | 4 +- direct/src/stdpy/threading2.py | 7 ++- direct/src/task/Task.py | 6 +-- direct/src/tkpanels/FSMInspector.py | 2 +- direct/src/tkpanels/Inspector.py | 8 +-- direct/src/tkwidgets/Tree.py | 2 +- direct/src/wxwidgets/ViewPort.py | 2 +- direct/src/wxwidgets/WxPandaWindow.py | 2 +- makepanda/makepanda.py | 21 +++++++- makepanda/makepandacore.py | 30 +++++++---- 43 files changed, 211 insertions(+), 172 deletions(-) diff --git a/direct/src/actor/Actor.py b/direct/src/actor/Actor.py index cfff9860d7..74cb07937f 100644 --- a/direct/src/actor/Actor.py +++ b/direct/src/actor/Actor.py @@ -2058,7 +2058,7 @@ class Actor(DirectObject, NodePath): if otherPartName != partName and otherPartDef.truePartName == parent: joints = self.getOverlappingJoints(partName, otherPartName) if joints: - raise StandardError, 'Overlapping joints: %s and %s' % (partName, otherPartName) + raise Exception('Overlapping joints: %s and %s' % (partName, otherPartName)) def setSubpartsComplete(self, flag): diff --git a/direct/src/directdevices/DirectRadamec.py b/direct/src/directdevices/DirectRadamec.py index 65880be00f..2f9a2495f1 100644 --- a/direct/src/directdevices/DirectRadamec.py +++ b/direct/src/directdevices/DirectRadamec.py @@ -77,7 +77,7 @@ class DirectRadamec(DirectObject): maxRange = self.maxRange[chan] minRange = self.minRange[chan] except IndexError: - raise RuntimeError, "can't normalize this channel (chanel %d)" % chan + raise RuntimeError("can't normalize this channel (channel %d)" % chan) range = maxRange - minRange clampedVal = CLAMP(self.aList[chan], minRange, maxRange) return ((maxVal - minVal) * (clampedVal - minRange) / range) + minVal diff --git a/direct/src/directnotify/Notifier.py b/direct/src/directnotify/Notifier.py index a49bbf0d03..a0dcc511ad 100644 --- a/direct/src/directnotify/Notifier.py +++ b/direct/src/directnotify/Notifier.py @@ -116,7 +116,7 @@ class Notifier: return NSError # error funcs - def error(self, errorString, exception=StandardError): + def error(self, errorString, exception=Exception): """ Raise an exception with given string and optional type: Exception: error diff --git a/direct/src/directscripts/gendocs.py b/direct/src/directscripts/gendocs.py index edf402382c..7770203de4 100644 --- a/direct/src/directscripts/gendocs.py +++ b/direct/src/directscripts/gendocs.py @@ -108,7 +108,7 @@ def findFiles(dirlist, ext, ign, list): for dir in dirlist: for file in os.listdir(dir): full = dir + "/" + file - if (ign.has_key(full)==0) and (ign.has_key(file)==0): + if full not in ign and file not in ign: if (os.path.isfile(full)): if (file.endswith(ext)): list.append(full) @@ -145,7 +145,7 @@ def textToHTML(comment, sep, delsection=None): sec = sec.replace(" "," ") if (delsection != None) and (delsection.match(sec)): included[sec] = 1 - if (included.has_key(sec)==0): + if sec not in included: included[sec] = 1 total = total + sec + "
\n" return total @@ -341,14 +341,14 @@ class InterrogateDatabase: def printTree(tree, indent): spacing = " "[:indent] if isinstance(tree, types.TupleType) and isinstance(tree[0], types.IntType): - if symbol.sym_name.has_key(tree[0]): + if tree[0] in symbol.sym_name: for i in range(len(tree)): if (i==0): print spacing + "(symbol." + symbol.sym_name[tree[0]] + "," else: printTree(tree[i], indent+1) print spacing + ")," - elif token.tok_name.has_key(tree[0]): + elif tree[0] in token.tok_name: print spacing + "(token." + token.tok_name[tree[0]] + ", '" + tree[1] + "')," else: print spacing + str(tree) @@ -535,10 +535,10 @@ class ParseTreeInfo: def extract_tokens(self, str, tree): if (isinstance(tree, types.TupleType)): - if (token.tok_name.has_key(tree[0])): + if tree[0] in token.tok_name: str = str + tree[1] if (tree[1]==","): str=str+" " - elif (symbol.sym_name.has_key(tree[0])): + elif tree[0] in symbol.sym_name: for sub in tree[1:]: str = self.extract_tokens(str, sub) return str @@ -569,7 +569,7 @@ class CodeDatabase: tokzr = InterrogateTokenizer(cxx) idb = InterrogateDatabase(tokzr) for type in idb.types.values(): - if (type.flags & 8192) or (self.types.has_key(type.scopedname)==0): + if (type.flags & 8192) or type.scopedname not in self.types: self.types[type.scopedname] = type if (type.flags & 8192) and (type.atomictype == 0) and (type.scopedname.count(" ")==0) and (type.scopedname.count(":")==0): self.goodtypes[type.scopedname] = type @@ -706,7 +706,7 @@ class CodeDatabase: def getFunctionPrototype(self, fn, urlprefix, urlsuffix): func = self.funcs.get(fn) if (isinstance(func, InterrogateFunction)): - if self.formattedprotos.has_key(fn): + if fn in self.formattedprotos: proto = self.formattedprotos[fn] else: proto = func.prototype @@ -864,7 +864,7 @@ def generate(pversion, indirlist, directdirlist, docdir, header, footer, urlpref body = body + generateFunctionDocs(code, method, urlprefix, urlsuffix) body = header + body + footer writeFile(docdir + "/" + type + ".html", body) - if (CLASS_RENAME_DICT.has_key(type)): + if type in CLASS_RENAME_DICT: modtype = CLASS_RENAME_DICT[type] writeFile(docdir + "/" + modtype + ".html", body) xclasses.append(modtype) @@ -892,8 +892,10 @@ def generate(pversion, indirlist, directdirlist, docdir, header, footer, urlpref for method in code.getClassMethods(type)[:]: name = code.getFunctionName(method) prefix = name[0].upper() - if (table.has_key(prefix)==0): table[prefix] = {} - if (table[prefix].has_key(name)==0): table[prefix][name] = [] + if prefix not in table: + table[prefix] = {} + if name not in table[prefix]: + table[prefix][name] = [] table[prefix][name].append(type) index = "

List of Methods - Panda " + pversion + "

\n" @@ -971,13 +973,13 @@ def expandImports(indirlist, directdirlist, fixdirlist): print fixfile+" : "+module+" : repairing" for x in funcExports: fn = code.getFunctionName(x) - if (used.has_key(fn)): + if fn in used: result.append("from "+module+" import "+fn) for x in typeExports: - if (used.has_key(x)): + if x in used: result.append("from "+module+" import "+x) for x in varExports: - if (used.has_key(x)): + if x in used: result.append("from "+module+" import "+x) else: result.append(line) diff --git a/direct/src/distributed/ConnectionRepository.py b/direct/src/distributed/ConnectionRepository.py index 3ff327a5b4..8af690357a 100644 --- a/direct/src/distributed/ConnectionRepository.py +++ b/direct/src/distributed/ConnectionRepository.py @@ -418,7 +418,7 @@ class ConnectionRepository( if hasattr(module, symbolName): dcImports[symbolName] = getattr(module, symbolName) else: - raise StandardError, 'Symbol %s not defined in module %s.' % (symbolName, moduleName) + raise Exception('Symbol %s not defined in module %s.' % (symbolName, moduleName)) else: # "import moduleName" diff --git a/direct/src/distributed/ServerRepository.py b/direct/src/distributed/ServerRepository.py index 613b88788f..7dcd5add72 100644 --- a/direct/src/distributed/ServerRepository.py +++ b/direct/src/distributed/ServerRepository.py @@ -192,7 +192,7 @@ class ServerRepository: dcImports[symbolName] = getattr(module, symbolName) else: - raise StandardError, 'Symbol %s not defined in module %s.' % (symbolName, moduleName) + raise Exception('Symbol %s not defined in module %s.' % (symbolName, moduleName)) else: # "import moduleName" diff --git a/direct/src/extensions_native/extension_native_helpers.py b/direct/src/extensions_native/extension_native_helpers.py index c6747e7272..d248f1f193 100644 --- a/direct/src/extensions_native/extension_native_helpers.py +++ b/direct/src/extensions_native/extension_native_helpers.py @@ -11,8 +11,10 @@ def Dtool_funcToMethod(func, cls, method_name=None): The new method is accessible to any instance immediately.""" if sys.version_info < (3, 0): func.im_class = cls - func.im_func = func - func.im_self = None + func.im_func = func + func.im_self = None + func.__func__ = func + func.__self__ = None if not method_name: method_name = func.__name__ cls.DtoolClassDict[method_name] = func diff --git a/direct/src/fsm/FSM.py b/direct/src/fsm/FSM.py index 1c0465b74d..2f9967783e 100644 --- a/direct/src/fsm/FSM.py +++ b/direct/src/fsm/FSM.py @@ -190,7 +190,7 @@ class FSM(DirectObject): def getCurrentFilter(self): if not self.state: error = "FSM cannot determine current filter while in transition (%s -> %s)." % (self.oldState, self.newState) - raise AlreadyInTransition, error + raise AlreadyInTransition(error) filter = getattr(self, "filter" + self.state, None) if not filter: @@ -276,7 +276,7 @@ class FSM(DirectObject): return if not self.request(request, *args): - raise RequestDenied, "%s (from state: %s)" % (request, self.state) + raise RequestDenied("%s (from state: %s)" % (request, self.state)) finally: self.fsmLock.release() @@ -310,7 +310,7 @@ class FSM(DirectObject): self.name, request, str(args)[1:])) filter = self.getCurrentFilter() - result = filter(request, args) + result = list(filter(request, args)) if result: if isinstance(result, types.StringTypes): # If the return value is a string, it's just the name @@ -381,7 +381,7 @@ class FSM(DirectObject): # request) not listed in defaultTransitions and not # handled by an earlier filter. if request[0].isupper(): - raise RequestDenied, "%s (from state: %s)" % (request, self.state) + raise RequestDenied("%s (from state: %s)" % (request, self.state)) # In either case, we quietly ignore unhandled command # (lowercase) requests. diff --git a/direct/src/fsm/State.py b/direct/src/fsm/State.py index 3be6501002..44a17080f8 100644 --- a/direct/src/fsm/State.py +++ b/direct/src/fsm/State.py @@ -30,18 +30,18 @@ class State(DirectObject): exitFunc = state.getExitFunc() # print 'testing: ', state, enterFunc, exitFunc, oldFunction if type(enterFunc) == types.MethodType: - if (enterFunc.im_func == oldFunction): + if enterFunc.__func__ == oldFunction: # print 'found: ', enterFunc, oldFunction state.setEnterFunc(types.MethodType(newFunction, - enterFunc.im_self, - enterFunc.im_class)) + enterFunc.__self__, + enterFunc.__self__.__class__)) count += 1 if type(exitFunc) == types.MethodType: - if (exitFunc.im_func == oldFunction): + if exitFunc.__func__ == oldFunction: # print 'found: ', exitFunc, oldFunction state.setExitFunc(types.MethodType(newFunction, - exitFunc.im_self, - exitFunc.im_class)) + exitFunc.__self__, + exitFunc.__self__.__class__)) count += 1 return count diff --git a/direct/src/gui/DirectGuiBase.py b/direct/src/gui/DirectGuiBase.py index 41322bcdff..2c67136535 100644 --- a/direct/src/gui/DirectGuiBase.py +++ b/direct/src/gui/DirectGuiBase.py @@ -258,8 +258,8 @@ class DirectGuiBase(DirectObject.DirectObject): text = 'Unknown option "' else: text = 'Unknown options "' - raise KeyError, text + ', '.join(unusedOptions) + \ - '" for ' + myClass.__name__ + raise KeyError(text + ', '.join(unusedOptions) + \ + '" for ' + myClass.__name__) # Can now call post init func self.postInitialiseFunc() @@ -399,8 +399,8 @@ class DirectGuiBase(DirectObject.DirectObject): if len(componentConfigFuncs) == 0 and \ component not in self._dynamicGroups: - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Add the configure method(s) (may be more than # one if this is configuring a component group) @@ -413,8 +413,8 @@ class DirectGuiBase(DirectObject.DirectObject): indirectOptions[componentConfigFunc][componentOption] \ = value else: - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Call the configure methods for any components. # Pass in the dictionary of keyword/values created above @@ -468,8 +468,8 @@ class DirectGuiBase(DirectObject.DirectObject): return componentCget(componentOption) # Option not found - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Allow index style refererences __getitem__ = cget @@ -481,8 +481,7 @@ class DirectGuiBase(DirectObject.DirectObject): """ # Check for invalid component name if '_' in componentName: - raise ValueError, \ - 'Component name "%s" must not contain "_"' % componentName + raise ValueError('Component name "%s" must not contain "_"' % componentName) # Get construction keywords if hasattr(self, '_constructorKeywords'): diff --git a/direct/src/gui/DirectScrollBar.py b/direct/src/gui/DirectScrollBar.py index a2a6f70ab2..acdc0a9c95 100644 --- a/direct/src/gui/DirectScrollBar.py +++ b/direct/src/gui/DirectScrollBar.py @@ -142,7 +142,7 @@ class DirectScrollBar(DirectFrame): elif self['orientation'] == DGG.VERTICAL_INVERTED: self.guiItem.setAxis(Vec3(0, 0, 1)) else: - raise ValueError, 'Invalid value for orientation: %s' % (self['orientation']) + raise ValueError('Invalid value for orientation: %s' % (self['orientation'])) def setManageButtons(self): self.guiItem.setManagePieces(self['manageButtons']) diff --git a/direct/src/gui/DirectSlider.py b/direct/src/gui/DirectSlider.py index 40737e6c9f..4fdc0588c8 100644 --- a/direct/src/gui/DirectSlider.py +++ b/direct/src/gui/DirectSlider.py @@ -111,7 +111,7 @@ class DirectSlider(DirectFrame): elif self['orientation'] == DGG.VERTICAL: self.guiItem.setAxis(Vec3(0, 0, 1)) else: - raise ValueError, 'Invalid value for orientation: %s' % (self['orientation']) + raise ValueError('Invalid value for orientation: %s' % (self['orientation'])) def destroy(self): if (hasattr(self, 'thumb')): diff --git a/direct/src/interval/FunctionInterval.py b/direct/src/interval/FunctionInterval.py index 2dc2d7686a..a730373916 100644 --- a/direct/src/interval/FunctionInterval.py +++ b/direct/src/interval/FunctionInterval.py @@ -34,11 +34,11 @@ class FunctionInterval(Interval.Interval): # print 'testing: ', ival.function, oldFunction # Note: you can only replace methods currently if type(ival.function) == types.MethodType: - if (ival.function.im_func == oldFunction): + if ival.function.__func__ == oldFunction: # print 'found: ', ival.function, oldFunction ival.function = types.MethodType(newFunction, - ival.function.im_self, - ival.function.im_class) + ival.function.__self__, + ival.function.__self__.__class__) count += 1 return count diff --git a/direct/src/interval/ProjectileInterval.py b/direct/src/interval/ProjectileInterval.py index d87253a5ad..9b8942d5ab 100755 --- a/direct/src/interval/ProjectileInterval.py +++ b/direct/src/interval/ProjectileInterval.py @@ -221,7 +221,7 @@ class ProjectileInterval(Interval): def testTrajectory(self): try: self.__calcTrajectory(*self.trajectoryArgs) - except StandardError: + except Exception: assert self.notify.error('invalid projectile parameters') return False return True diff --git a/direct/src/p3d/AppRunner.py b/direct/src/p3d/AppRunner.py index 9c6c15631a..0fd46de469 100644 --- a/direct/src/p3d/AppRunner.py +++ b/direct/src/p3d/AppRunner.py @@ -798,7 +798,7 @@ class AppRunner(DirectObject): if not host.hasContentsFile: # This is weird. How did we launch without having # this file at all? - raise OSError, message + raise OSError(message) # Just make it a warning and continue. self.notify.warning(message) @@ -819,20 +819,20 @@ class AppRunner(DirectObject): return self.addPackageInfo(name, platform, version, hostUrl, hostDir = hostDir, recurse = True) message = "Couldn't find %s %s on %s" % (name, version, hostUrl) - raise OSError, message + raise OSError(message) package.checkStatus() if not package.downloadDescFile(self.http): message = "Couldn't get desc file for %s" % (name) - raise OSError, message + raise OSError(message) if not package.downloadPackage(self.http): message = "Couldn't download %s" % (name) - raise OSError, message + raise OSError(message) if not package.installPackage(self): message = "Couldn't install %s" % (name) - raise OSError, message + raise OSError(message) if package.guiApp: self.guiApp = True @@ -877,17 +877,17 @@ class AppRunner(DirectObject): vfs = VirtualFileSystem.getGlobalPtr() if not vfs.exists(fname): - raise ArgumentError, "No such file: %s" % (p3dFilename) + raise ArgumentError("No such file: %s" % (p3dFilename)) fname.makeAbsolute() fname.setBinary() mf = Multifile() if p3dOffset == 0: if not mf.openRead(fname): - raise ArgumentError, "Not a Panda3D application: %s" % (p3dFilename) + raise ArgumentError("Not a Panda3D application: %s" % (p3dFilename)) else: if not mf.openRead(fname, p3dOffset): - raise ArgumentError, "Not a Panda3D application: %s at offset: %s" % (p3dFilename, p3dOffset) + raise ArgumentError("Not a Panda3D application: %s at offset: %s" % (p3dFilename, p3dOffset)) # Now load the p3dInfo file. self.p3dInfo = None @@ -925,7 +925,7 @@ class AppRunner(DirectObject): # The interactiveConsole flag can only be set true if the # application has allow_python_dev set. if not self.allowPythonDev and interactiveConsole: - raise StandardError, "Impossible, interactive_console set without allow_python_dev." + raise Exception("Impossible, interactive_console set without allow_python_dev.") self.interactiveConsole = interactiveConsole if self.allowPythonDev: diff --git a/direct/src/p3d/JavaScript.py b/direct/src/p3d/JavaScript.py index 3b6d295032..3208b7d7ba 100644 --- a/direct/src/p3d/JavaScript.py +++ b/direct/src/p3d/JavaScript.py @@ -13,9 +13,11 @@ class UndefinedObject: attributes, similar to None, but it is a slightly different concept in JavaScript. """ - def __nonzero__(self): + def __bool__(self): return False + __nonzero__ = __bool__ # Python 2 + def __str__(self): return "Undefined" @@ -83,16 +85,18 @@ class BrowserObject: def __str__(self): return self.toString() - def __nonzero__(self): + def __bool__(self): return True + __nonzero__ = __bool__ # Python 2 + def __call__(self, *args, **kw): needsResponse = True if 'needsResponse' in kw: needsResponse = kw['needsResponse'] del kw['needsResponse'] if kw: - raise ArgumentError, 'Keyword arguments not supported' + raise ArgumentError('Keyword arguments not supported') try: parentObj, attribName = self.__childObject @@ -242,16 +246,18 @@ class MethodWrapper: parentObj, attribName = self.__childObject return "%s.%s" % (parentObj, attribName) - def __nonzero__(self): + def __bool__(self): return True + __nonzero__ = __bool__ # Python 2 + def __call__(self, *args, **kw): needsResponse = True if 'needsResponse' in kw: needsResponse = kw['needsResponse'] del kw['needsResponse'] if kw: - raise ArgumentError, 'Keyword arguments not supported' + raise ArgumentError('Keyword arguments not supported') try: parentObj, attribName = self.__childObject diff --git a/direct/src/p3d/PackageInstaller.py b/direct/src/p3d/PackageInstaller.py index 33527ef94e..cec1e07b11 100644 --- a/direct/src/p3d/PackageInstaller.py +++ b/direct/src/p3d/PackageInstaller.py @@ -239,7 +239,7 @@ class PackageInstaller(DirectObject): downloaded. Call donePackages() to finish the list. """ if self.state != self.S_initial: - raise ValueError, 'addPackage called after donePackages' + raise ValueError('addPackage called after donePackages') host = self.appRunner.getHostWithAlt(hostUrl) pp = self.PendingPackage(packageName, version, host) diff --git a/direct/src/p3d/PackageMerger.py b/direct/src/p3d/PackageMerger.py index a00a3f7d35..9c2e1ac499 100644 --- a/direct/src/p3d/PackageMerger.py +++ b/direct/src/p3d/PackageMerger.py @@ -7,7 +7,7 @@ from panda3d.core import * import shutil import os -class PackageMergerError(StandardError): +class PackageMergerError(Exception): pass class PackageMerger: @@ -102,12 +102,12 @@ class PackageMerger: doc = TiXmlDocument(packageDescFullpath.toOsSpecific()) if not doc.LoadFile(): message = "Could not read XML file: %s" % (self.descFile.filename) - raise OSError, message + raise OSError(message) xpackage = doc.FirstChildElement('package') if not xpackage: message = "No package definition: %s" % (self.descFile.filename) - raise OSError, message + raise OSError(message) xcompressed = xpackage.FirstChildElement('compressed_archive') if xcompressed: @@ -286,7 +286,7 @@ class PackageMerger: if not self.__readContentsFile(sourceDir, packageNames): message = "Couldn't read %s" % (sourceDir) - raise PackageMergerError, message + raise PackageMergerError(message) def close(self): """ Finalizes the results of all of the previous calls to diff --git a/direct/src/p3d/Packager.py b/direct/src/p3d/Packager.py index f7d6855a90..2f1e6a36e1 100644 --- a/direct/src/p3d/Packager.py +++ b/direct/src/p3d/Packager.py @@ -26,7 +26,7 @@ from direct.directnotify.DirectNotifyGlobal import * vfs = VirtualFileSystem.getGlobalPtr() -class PackagerError(StandardError): +class PackagerError(Exception): pass class OutsideOfPackageError(PackagerError): @@ -390,7 +390,7 @@ class Packager: if not self.p3dApplication and not self.packager.allowPackages: message = 'Cannot generate packages without an installDir; use -i' - raise PackagerError, message + raise PackagerError(message) if self.ignoredDirFiles: exts = sorted(self.ignoredDirFiles.keys()) @@ -429,11 +429,11 @@ class Packager: if self.version != PandaSystem.getPackageVersionString(): message = 'mismatched Panda3D version: requested %s, but Panda3D is built as %s' % (self.version, PandaSystem.getPackageVersionString()) - raise PackagerError, message + raise PackagerError(message) if self.host != PandaSystem.getPackageHostUrl(): message = 'mismatched Panda3D host: requested %s, but Panda3D is built as %s' % (self.host, PandaSystem.getPackageHostUrl()) - raise PackagerError, message + raise PackagerError(message) if self.p3dApplication: # Default compression level for an app. @@ -554,7 +554,7 @@ class Packager: # Add the main module, if any. if not self.mainModule and self.p3dApplication: message = 'No main_module specified for application %s' % (self.packageName) - raise PackagerError, message + raise PackagerError(message) if self.mainModule: moduleName, newName = self.mainModule if newName not in self.freezer.modules: @@ -790,7 +790,7 @@ class Packager: if not self.packager.allowPackages: message = 'Cannot generate packages without an installDir; use -i' - raise PackagerError, message + raise PackagerError(message) installPath = Filename(self.packager.installDir, packageDir) # Remove any files already in the installPath. @@ -811,7 +811,7 @@ class Packager: return if len(files) != 1: - raise PackagerError, 'Multiple files in "solo" package %s' % (self.packageName) + raise PackagerError('Multiple files in "solo" package %s' % (self.packageName)) Filename(installPath, '').makeDir() @@ -1535,7 +1535,7 @@ class Packager: compressedPath = Filename(self.packager.installDir, newCompressedFilename) if not compressFile(self.packageFullpath, compressedPath, 6): message = 'Unable to write %s' % (compressedPath) - raise PackagerError, message + raise PackagerError(message) def readDescFile(self): """ Reads the existing package.xml file before rewriting @@ -1838,7 +1838,7 @@ class Packager: if parentName not in self.freezer.modules: message = 'Cannot add Python file %s; not in package' % (file.newName) if file.required or file.explicit: - raise StandardError, message + raise Exception(message) else: self.notify.warning(message) return @@ -1852,7 +1852,7 @@ class Packager: # Precompile egg files to bam's. np = self.packager.loader.loadModel(file.filename) if not np: - raise StandardError, 'Could not read egg file %s' % (file.filename) + raise Exception('Could not read egg file %s' % (file.filename)) bamName = Filename(file.newName) bamName.setExtension('bam') @@ -1862,14 +1862,14 @@ class Packager: # Load the bam file so we can massage its textures. bamFile = BamFile() if not bamFile.openRead(file.filename): - raise StandardError, 'Could not read bam file %s' % (file.filename) + raise Exception('Could not read bam file %s' % (file.filename)) if not bamFile.resolve(): - raise StandardError, 'Could not resolve bam file %s' % (file.filename) + raise Exception('Could not resolve bam file %s' % (file.filename)) node = bamFile.readNode() if not node: - raise StandardError, 'Not a model file: %s' % (file.filename) + raise Exception('Not a model file: %s' % (file.filename)) self.addNode(node, file.filename, file.newName) @@ -2703,7 +2703,7 @@ class Packager: self.allowPackages = False if not PandaSystem.getPackageVersionString() or not PandaSystem.getPackageHostUrl(): - raise PackagerError, 'This script must be run using a version of Panda3D that has been built\nfor distribution. Try using ppackage.p3d or packp3d.p3d instead.\nIf you are running this script for development purposes, you may also\nset the Config variable panda-package-host-url to the URL you expect\nto download these contents from (for instance, a file:// URL).' + raise PackagerError('This script must be run using a version of Panda3D that has been built\nfor distribution. Try using ppackage.p3d or packp3d.p3d instead.\nIf you are running this script for development purposes, you may also\nset the Config variable panda-package-host-url to the URL you expect\nto download these contents from (for instance, a file:// URL).') self.readContentsFile() @@ -2804,7 +2804,7 @@ class Packager: self.notify.info("No files added to %s" % (name)) for (lineno, stype, sname, args, kw) in statements: if stype == 'class': - raise PackagerError, 'Nested classes not allowed' + raise PackagerError('Nested classes not allowed') self.__evalFunc(sname, args, kw) package = self.endPackage() if package is not None: @@ -2812,7 +2812,7 @@ class Packager: elif packageNames is not None: # If the name is explicitly specified, this means # we should abort if the package faild to construct. - raise PackagerError, 'Failed to construct %s' % name + raise PackagerError('Failed to construct %s' % name) else: self.__evalFunc(name, args, kw) except PackagerError: @@ -2838,7 +2838,7 @@ class Packager: func(*args, **kw) except OutsideOfPackageError: message = '%s encountered outside of package definition' % (name) - raise OutsideOfPackageError, message + raise OutsideOfPackageError(message) def __expandTabs(self, line, tabWidth = 8): """ Expands tab characters in the line to 8 spaces. """ @@ -2883,10 +2883,10 @@ class Packager: value = value.strip() if parameter not in argList: message = 'Unknown parameter %s' % (parameter) - raise PackagerError, message + raise PackagerError(message) if parameter in args: message = 'Duplicate parameter %s' % (parameter) - raise PackagerError, message + raise PackagerError(message) args[parameter] = value @@ -2900,7 +2900,7 @@ class Packager: to file() etc., and close the package with endPackage(). """ if self.currentPackage: - raise PackagerError, 'unclosed endPackage %s' % (self.currentPackage.packageName) + raise PackagerError('unclosed endPackage %s' % (self.currentPackage.packageName)) package = self.Package(packageName, self) self.currentPackage = package @@ -2910,7 +2910,7 @@ class Packager: if not package.p3dApplication and not self.allowPackages: message = 'Cannot generate packages without an installDir; use -i' - raise PackagerError, message + raise PackagerError(message) def endPackage(self): @@ -2919,7 +2919,7 @@ class Packager: or None if the package failed to close (e.g. missing files). """ if not self.currentPackage: - raise PackagerError, 'unmatched endPackage' + raise PackagerError('unmatched endPackage') package = self.currentPackage package.signParams += self.signParams[:] @@ -3310,7 +3310,7 @@ class Packager: raise OutsideOfPackageError if (newName or filename) and len(moduleNames) != 1: - raise PackagerError, 'Cannot specify newName with multiple modules' + raise PackagerError('Cannot specify newName with multiple modules') if required: self.currentPackage.requiredModules += moduleNames @@ -3469,7 +3469,7 @@ class Packager: package.mainModule = None if not package.mainModule and compileToExe: message = "No main_module specified for exe %s" % (filename) - raise PackagerError, message + raise PackagerError(message) if package.mainModule: moduleName, newName = package.mainModule @@ -3641,12 +3641,12 @@ class Packager: if newName: if len(files) != 1: message = 'Cannot install multiple files on target filename %s' % (newName) - raise PackagerError, message + raise PackagerError(message) if text: if len(files) != 1: message = 'Cannot install text to multiple files' - raise PackagerError, message + raise PackagerError(message) if not newName: newName = str(filenames[0]) diff --git a/direct/src/p3d/PatchMaker.py b/direct/src/p3d/PatchMaker.py index 7055f5eb3e..485ad0d0e9 100644 --- a/direct/src/p3d/PatchMaker.py +++ b/direct/src/p3d/PatchMaker.py @@ -765,7 +765,7 @@ class PatchMaker: filename = Filename(package.currentFile.filename + '.%s.patch' % (package.patchVersion)) assert filename not in self.patchFilenames if not self.buildPatch(topPv, currentPv, package, filename): - raise StandardError, "Couldn't build patch." + raise Exception("Couldn't build patch.") def buildPatch(self, v1, v2, package, patchFilename): """ Builds a patch from PackageVersion v1 to PackageVersion @@ -780,7 +780,7 @@ class PatchMaker: compressedPathname = Filename(pathname + '.pz') compressedPathname.unlink() if not compressFile(pathname, compressedPathname, 9): - raise StandardError, "Couldn't compress patch." + raise Exception("Couldn't compress patch.") pathname.unlink() patchfile = self.Patchfile(package) diff --git a/direct/src/p3d/SeqValue.py b/direct/src/p3d/SeqValue.py index c146944dfa..d41cfd250b 100644 --- a/direct/src/p3d/SeqValue.py +++ b/direct/src/p3d/SeqValue.py @@ -26,7 +26,7 @@ class SeqValue: elif isinstance(value, types.StringTypes): self.setFromString(value) else: - raise TypeError, 'Invalid sequence type: %s' % (value,) + raise TypeError('Invalid sequence type: %s' % (value,)) def setFromTuple(self, value): """ Sets the seq from the indicated tuple of integers. """ diff --git a/direct/src/p3d/packp3d.py b/direct/src/p3d/packp3d.py index e1cebf2137..a33a49e2d4 100755 --- a/direct/src/p3d/packp3d.py +++ b/direct/src/p3d/packp3d.py @@ -107,7 +107,7 @@ from panda3d.core import * # Temp hack for debugging. #from direct.p3d.AppRunner import dummyAppRunner; dummyAppRunner() -class ArgumentError(StandardError): +class ArgumentError(Exception): pass def makePackedApp(args): @@ -167,13 +167,13 @@ def makePackedApp(args): sys.exit(0) if not appFilename: - raise ArgumentError, "No target app specified. Use:\n %s -o app.p3d\nUse -h to get more usage information." % (os.path.split(sys.argv[0])[1]) + raise ArgumentError("No target app specified. Use:\n %s -o app.p3d\nUse -h to get more usage information." % (os.path.split(sys.argv[0])[1])) if args: - raise ArgumentError, "Extra arguments on command line." + raise ArgumentError("Extra arguments on command line.") if appFilename.getExtension() != 'p3d': - raise ArgumentError, 'Application filename must end in ".p3d".' + raise ArgumentError('Application filename must end in ".p3d".') appDir = Filename(appFilename.getDirname()) if not appDir: @@ -188,9 +188,9 @@ def makePackedApp(args): if not main.exists(): main = glob.glob(os.path.join(root.toOsSpecific(), '*.py')) if len(main) == 0: - raise ArgumentError, 'No Python files in root directory.' + raise ArgumentError('No Python files in root directory.') elif len(main) > 1: - raise ArgumentError, 'Multiple Python files in root directory; specify the main application with -m "main".' + raise ArgumentError('Multiple Python files in root directory; specify the main application with -m "main".') main = Filename.fromOsSpecific(os.path.split(main[0])[1]) main.makeAbsolute(root) diff --git a/direct/src/p3d/runp3d.py b/direct/src/p3d/runp3d.py index e561e73a0f..167f8d0d2f 100644 --- a/direct/src/p3d/runp3d.py +++ b/direct/src/p3d/runp3d.py @@ -46,7 +46,7 @@ def parseSysArgs(): sys.exit(1) if not args or not args[0]: - raise ArgumentError, "No Panda app specified. Use:\nrunp3d.py app.p3d" + raise ArgumentError("No Panda app specified. Use:\nrunp3d.py app.p3d") arg0 = args[0] p3dFilename = Filename.fromOsSpecific(arg0) diff --git a/direct/src/plugin_npapi/make_osx_bundle.py b/direct/src/plugin_npapi/make_osx_bundle.py index 8d83b35310..e4b9f365a6 100755 --- a/direct/src/plugin_npapi/make_osx_bundle.py +++ b/direct/src/plugin_npapi/make_osx_bundle.py @@ -33,7 +33,7 @@ def makeBundle(startDir): path.appendPath(os.environ['DYLD_LIBRARY_PATH']) nppanda3d = path.findFile('nppanda3d') if not nppanda3d: - raise StandardError, "Couldn't find nppanda3d on path." + raise Exception("Couldn't find nppanda3d on path.") # Generate the bundle directory structure rootFilename = Filename(fstartDir, 'bundle') @@ -54,7 +54,7 @@ def makeBundle(startDir): resourceFilename.toOsSpecific(), Filename(fstartDir, "nppanda3d.r").toOsSpecific())) if not resourceFilename.exists(): - raise IOError, 'Unable to run Rez' + raise IOError('Unable to run Rez') # Copy in Info.plist and the compiled executable. shutil.copyfile(Filename(fstartDir, "nppanda3d.plist").toOsSpecific(), plistFilename.toOsSpecific()) diff --git a/direct/src/plugin_standalone/make_osx_bundle.py b/direct/src/plugin_standalone/make_osx_bundle.py index 20807f6974..2fe846a3c3 100755 --- a/direct/src/plugin_standalone/make_osx_bundle.py +++ b/direct/src/plugin_standalone/make_osx_bundle.py @@ -32,7 +32,7 @@ def makeBundle(startDir): path.appendPath(os.defpath) panda3d_mac = path.findFile('panda3d_mac') if not panda3d_mac: - raise StandardError, "Couldn't find panda3d_mac on path." + raise Exception("Couldn't find panda3d_mac on path.") # Construct a search path to look for the images. search = DSearchPath() @@ -53,7 +53,7 @@ def makeBundle(startDir): # Now find the icon file on the above search path. icons = search.findFile('panda3d.icns') if not icons: - raise StandardError, "Couldn't find panda3d.icns on model-path." + raise Exception("Couldn't find panda3d.icns on model-path.") # Generate the bundle directory structure rootFilename = Filename(fstartDir) diff --git a/direct/src/showbase/Audio3DManager.py b/direct/src/showbase/Audio3DManager.py index 270a7e56c4..5a4fdc295b 100644 --- a/direct/src/showbase/Audio3DManager.py +++ b/direct/src/showbase/Audio3DManager.py @@ -123,7 +123,7 @@ class Audio3DManager: Default: VBase3(0, 0, 0) """ if not isinstance(velocity, VBase3): - raise TypeError, "Invalid argument 1, expected " + raise TypeError("Invalid argument 1, expected ") self.vel_dict[sound]=velocity def setSoundVelocityAuto(self, sound): @@ -156,7 +156,7 @@ class Audio3DManager: Default: VBase3(0, 0, 0) """ if not isinstance(velocity, VBase3): - raise TypeError, "Invalid argument 0, expected " + raise TypeError("Invalid argument 0, expected ") self.listener_vel=velocity def setListenerVelocityAuto(self): diff --git a/direct/src/showbase/Loader.py b/direct/src/showbase/Loader.py index 94bc5d4e14..9521df23ef 100644 --- a/direct/src/showbase/Loader.py +++ b/direct/src/showbase/Loader.py @@ -324,7 +324,7 @@ class Loader(DirectObject): nodeList[i] = nodeList[i].node() # From here on, we deal with a list of (filename, node) pairs. - modelList = zip(modelList, nodeList) + modelList = list(zip(modelList, nodeList)) if callback is None: # We got no callback, so it's a synchronous save. diff --git a/direct/src/showbase/Messenger.py b/direct/src/showbase/Messenger.py index aba83d7d3a..e9f9241646 100644 --- a/direct/src/showbase/Messenger.py +++ b/direct/src/showbase/Messenger.py @@ -132,7 +132,7 @@ class Messenger: # Make sure extraArgs is a list or tuple if not (isinstance(extraArgs, list) or isinstance(extraArgs, tuple) or isinstance(extraArgs, set)): - raise TypeError, "A list is required as extraArgs argument" + raise TypeError("A list is required as extraArgs argument") self.lock.acquire() try: @@ -442,7 +442,7 @@ class Messenger: object, params = objectEntry method = params[0] if (type(method) == types.MethodType): - function = method.im_func + function = method.__func__ else: function = method #print ('function: ' + repr(function) + '\n' + @@ -451,7 +451,7 @@ class Messenger: # 'newFunction: ' + repr(newFunction) + '\n') if (function == oldMethod): newMethod = types.MethodType( - newFunction, method.im_self, method.im_class) + newFunction, method.__self__, method.__self__.__class__) params[0] = newMethod # Found it retrun true retFlag += 1 @@ -560,8 +560,8 @@ class Messenger: return string version of class.method or method. """ if (type(method) == types.MethodType): - functionName = method.im_class.__name__ + '.' + \ - method.im_func.__name__ + functionName = method.__self__.__class__.__name__ + '.' + \ + method.__func__.__name__ else: if hasattr(method, "__name__"): functionName = method.__name__ @@ -629,7 +629,7 @@ class Messenger: if (type(function) == types.MethodType): str = (str + '\t' + 'Method: ' + repr(function) + '\n\t' + - 'Function: ' + repr(function.im_func) + '\n') + 'Function: ' + repr(function.__func__) + '\n') else: str = (str + '\t' + 'Function: ' + repr(function) + '\n') diff --git a/direct/src/showbase/PythonUtil.py b/direct/src/showbase/PythonUtil.py index 3e8e8aa581..e1750cf21f 100644 --- a/direct/src/showbase/PythonUtil.py +++ b/direct/src/showbase/PythonUtil.py @@ -660,7 +660,7 @@ if __debug__: def profileDecorator(f): def _profiled(*args, **kArgs): - name = '(%s) %s from %s' % (category, f.func_name, f.__module__) + name = '(%s) %s from %s' % (category, f.__name__, f.__module__) # showbase might not be loaded yet, so don't use # base.config. Instead, query the ConfigVariableBool. @@ -1265,12 +1265,12 @@ class Enum: invalidChars = invalidChars.replace('_','') invalidFirstChars = invalidChars+string.digits if item[0] in invalidFirstChars: - raise SyntaxError, ("Enum '%s' contains invalid first char" % + raise SyntaxError("Enum '%s' contains invalid first char" % item) if not disjoint(item, invalidChars): for char in item: if char in invalidChars: - raise SyntaxError, ( + raise SyntaxError( "Enum\n'%s'\ncontains illegal char '%s'" % (item, char)) return 1 @@ -2070,7 +2070,7 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')' - outStr = '%s%s' % (f.func_name, rArgs) + outStr = '%s%s' % (f.__name__, rArgs) # Insert prefix place holder, if needed if prefixes: @@ -2127,9 +2127,9 @@ def report(types = [], prefix = '', xform = None, notifyFunc = None, dConfigPara pass return rVal - wrap.func_name = f.func_name - wrap.func_dict = f.func_dict - wrap.func_doc = f.func_doc + wrap.__name__ = f.__name__ + wrap.__dict__ = f.__dict__ + wrap.__doc__ = f.__doc__ wrap.__module__ = f.__module__ return wrap return decorator @@ -2179,7 +2179,7 @@ if __debug__: return f(*args, **kArgs) except Exception, e: try: - s = '%s(' % f.func_name + s = '%s(' % f.__name__ for arg in args: s += '%s, ' % arg for key, value in kArgs.items(): @@ -2193,7 +2193,7 @@ if __debug__: exceptionLoggedNotify.info(s) except: exceptionLoggedNotify.info( - '%s: ERROR IN PRINTING' % f.func_name) + '%s: ERROR IN PRINTING' % f.__name__) raise _exceptionLogged.__doc__ = f.__doc__ return _exceptionLogged diff --git a/direct/src/showbase/RandomNumGen.py b/direct/src/showbase/RandomNumGen.py index 0b6df19d2b..da95bbabee 100644 --- a/direct/src/showbase/RandomNumGen.py +++ b/direct/src/showbase/RandomNumGen.py @@ -96,30 +96,30 @@ class RandomNumGen: # common case while still doing adequate error checking istart = int(start) if istart != start: - raise ValueError, "non-integer arg 1 for randrange()" + raise ValueError("non-integer arg 1 for randrange()") if stop is None: if istart > 0: return self.__rand(istart) - raise ValueError, "empty range for randrange()" + raise ValueError("empty range for randrange()") istop = int(stop) if istop != stop: - raise ValueError, "non-integer stop for randrange()" + raise ValueError("non-integer stop for randrange()") if step == 1: if istart < istop: return istart + self.__rand(istop - istart) - raise ValueError, "empty range for randrange()" + raise ValueError("empty range for randrange()") istep = int(step) if istep != step: - raise ValueError, "non-integer step for randrange()" + raise ValueError("non-integer step for randrange()") if istep > 0: n = (istop - istart + istep - 1) / istep elif istep < 0: n = (istop - istart + istep + 1) / istep else: - raise ValueError, "zero step for randrange()" + raise ValueError("zero step for randrange()") if n <= 0: - raise ValueError, "empty range for randrange()" + raise ValueError("empty range for randrange()") return istart + istep*int(self.__rand(n)) def randint(self, a, b): diff --git a/direct/src/showbase/ShowBase.py b/direct/src/showbase/ShowBase.py index 28aa140e8e..f9f8068683 100644 --- a/direct/src/showbase/ShowBase.py +++ b/direct/src/showbase/ShowBase.py @@ -338,7 +338,7 @@ class ShowBase(DirectObject.DirectObject): # Make sure we're not making more than one ShowBase. if hasattr(builtins, 'base'): - raise StandardError, "Attempt to spawn multiple ShowBase instances!" + raise Exception("Attempt to spawn multiple ShowBase instances!") # DO NOT ADD TO THIS LIST. We're trying to phase out the use of # built-in variables by ShowBase. Use a Global module if necessary. @@ -695,7 +695,7 @@ class ShowBase(DirectObject.DirectObject): if requireWindow: # Unless require-window is set to false, it is an # error not to open a window. - raise StandardError, 'Could not open window.' + raise Exception('Could not open window.') else: self.notify.info("Successfully opened window of type %s (%s)" % ( win.getType(), win.getPipe().getInterfaceName())) @@ -2519,7 +2519,7 @@ class ShowBase(DirectObject.DirectObject): rig = NodePath(namePrefix) buffer = source.makeCubeMap(namePrefix, size, rig, cameraMask, 1) if buffer == None: - raise StandardError, "Could not make cube map." + raise Exception("Could not make cube map.") # Set the near and far planes from the default lens. lens = rig.find('**/+Camera').node().getLens() @@ -2589,7 +2589,7 @@ class ShowBase(DirectObject.DirectObject): buffer = toSphere.makeCubeMap(namePrefix, size, rig, cameraMask, 0) if buffer == None: self.graphicsEngine.removeWindow(toSphere) - raise StandardError, "Could not make cube map." + raise Exception("Could not make cube map.") # Set the near and far planes from the default lens. lens = rig.find('**/+Camera').node().getLens() diff --git a/direct/src/showutil/FreezeTool.py b/direct/src/showutil/FreezeTool.py index 286e56ba9d..9862e1c764 100644 --- a/direct/src/showutil/FreezeTool.py +++ b/direct/src/showutil/FreezeTool.py @@ -171,7 +171,7 @@ class CompilationEnvironment: } print >> sys.stderr, compile if os.system(compile) != 0: - raise StandardError, 'failed to compile %s.' % basename + raise Exception('failed to compile %s.' % basename) link = self.linkExe % { 'python' : self.Python, @@ -186,7 +186,7 @@ class CompilationEnvironment: } print >> sys.stderr, link if os.system(link) != 0: - raise StandardError, 'failed to link %s.' % basename + raise Exception('failed to link %s.' % basename) def compileDll(self, filename, basename): compile = self.compileObj % { @@ -203,7 +203,7 @@ class CompilationEnvironment: } print >> sys.stderr, compile if os.system(compile) != 0: - raise StandardError, 'failed to compile %s.' % basename + raise Exception('failed to compile %s.' % basename) link = self.linkDll % { 'python' : self.Python, @@ -219,7 +219,7 @@ class CompilationEnvironment: } print >> sys.stderr, link if os.system(link) != 0: - raise StandardError, 'failed to link %s.' % basename + raise Exception('failed to link %s.' % basename) # The code from frozenmain.c in the Python source repository. frozenMainCode = """ @@ -1207,7 +1207,7 @@ class Freezer: Filename(mfname).unlink() multifile = Multifile() if not multifile.openReadWrite(mfname): - raise StandardError + raise Exception self.addToMultifile(multifile) @@ -1284,7 +1284,7 @@ class Freezer: # We must have a __main__ module to make an exe file. if not self.__writingModule('__main__'): message = "Can't generate an executable without a __main__ module." - raise StandardError, message + raise Exception(message) filename = basename + self.sourceExtension @@ -1407,9 +1407,11 @@ class PandaModuleFinder(modulefinder.ModuleFinder): return (None, name, ('', '', imp.PY_FROZEN)) message = "DLL loader cannot find %s." % (name) - raise ImportError, message + raise ImportError(message) + + def load_module(self, fqname, fp, pathname, file_info): + suffix, mode, type = file_info - def load_module(self, fqname, fp, pathname, (suffix, mode, type)): if type == imp.PY_FROZEN: # It's a frozen module. co, isPackage = p3extend_frozen.get_frozen_module_code(pathname) diff --git a/direct/src/stdpy/glob.py b/direct/src/stdpy/glob.py index 3d1cce60f4..6f825a4561 100755 --- a/direct/src/stdpy/glob.py +++ b/direct/src/stdpy/glob.py @@ -61,7 +61,7 @@ def glob1(dirname, pattern): except os.error: return [] if pattern[0] != '.': - names = filter(lambda x: x[0] != '.', names) + names = [x for x in names if x[0] != '.'] return fnmatch.filter(names, pattern) def glob0(dirname, basename): diff --git a/direct/src/stdpy/thread.py b/direct/src/stdpy/thread.py index f8291488d1..ccbc141b5b 100644 --- a/direct/src/stdpy/thread.py +++ b/direct/src/stdpy/thread.py @@ -21,7 +21,7 @@ from panda3d import core forceYield = core.Thread.forceYield considerYield = core.Thread.considerYield -class error(StandardError): +class error(Exception): pass class LockType: @@ -54,7 +54,7 @@ class LockType: self.__lock.acquire() try: if not self.__locked: - raise error, 'Releasing unheld lock.' + raise error('Releasing unheld lock.') self.__locked = False self.__cvar.notify() diff --git a/direct/src/stdpy/threading2.py b/direct/src/stdpy/threading2.py index d03ac01c3c..b9df97ca97 100644 --- a/direct/src/stdpy/threading2.py +++ b/direct/src/stdpy/threading2.py @@ -139,10 +139,9 @@ class _RLock(_Verbose): # Internal methods used by condition variables - def _acquire_restore(self, (count, owner)): + def _acquire_restore(self, state): self.__block.acquire() - self.__count = count - self.__owner = owner + self.__count, self.__owner = state if __debug__: self._note("%s._acquire_restore()", self) @@ -334,7 +333,7 @@ class _BoundedSemaphore(_Semaphore): def release(self): if self._Semaphore__value >= self._initial_value: - raise ValueError, "Semaphore released too many times" + raise ValueError("Semaphore released too many times") return _Semaphore.release(self) diff --git a/direct/src/task/Task.py b/direct/src/task/Task.py index 5d4a831f32..bce3b127e1 100644 --- a/direct/src/task/Task.py +++ b/direct/src/task/Task.py @@ -571,13 +571,13 @@ class TaskManager: method = task.getFunction() if (type(method) == types.MethodType): - function = method.im_func + function = method.__func__ else: function = method if (function == oldMethod): newMethod = types.MethodType(newFunction, - method.im_self, - method.im_class) + method.__self__, + method.__self__.__class__) task.setFunction(newMethod) # Found a match return 1 diff --git a/direct/src/tkpanels/FSMInspector.py b/direct/src/tkpanels/FSMInspector.py index 398cd1583f..f6c5cc258e 100644 --- a/direct/src/tkpanels/FSMInspector.py +++ b/direct/src/tkpanels/FSMInspector.py @@ -151,7 +151,7 @@ class FSMInspector(AppShell): toCenter, self.computePoint(toState.radius, angle - DELTA)) - return newFromPt + newToPt + return list(newFromPt) + list(newToPt) def computePoint(self, radius, angle): x = radius * math.cos(angle) diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index 47d3b4f6a6..98e4378e30 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -166,7 +166,7 @@ class FunctionInspector(Inspector): class InstanceMethodInspector(Inspector): def title(self): - return str(self.object.im_class) + "." + self.object.__name__ + "()" + return str(self.object.__self__.__class__) + "." + self.object.__name__ + "()" class CodeInspector(Inspector): def title(self): @@ -391,10 +391,10 @@ class InspectorWindow: #Private def selectedIndex(self): - indicies = map(int, self.listWidget.curselection()) - if len(indicies) == 0: + indices = list(map(int, self.listWidget.curselection())) + if len(indices) == 0: return None - partNumber = indicies[0] + partNumber = indices[0] return partNumber def inspectorForSelectedPart(self): diff --git a/direct/src/tkwidgets/Tree.py b/direct/src/tkwidgets/Tree.py index 7e864aaad3..88d3918386 100644 --- a/direct/src/tkwidgets/Tree.py +++ b/direct/src/tkwidgets/Tree.py @@ -27,7 +27,7 @@ from panda3d.core import * # Initialize icon directory ICONDIR = ConfigVariableSearchPath('model-path').findFile(Filename('icons')).toOsSpecific() if not os.path.isdir(ICONDIR): - raise RuntimeError, "can't find DIRECT icon directory (%s)" % repr(ICONDIR) + raise RuntimeError("can't find DIRECT icon directory (%s)" % repr(ICONDIR)) class TreeNode: diff --git a/direct/src/wxwidgets/ViewPort.py b/direct/src/wxwidgets/ViewPort.py index b0d03d88c9..19ed102330 100755 --- a/direct/src/wxwidgets/ViewPort.py +++ b/direct/src/wxwidgets/ViewPort.py @@ -171,7 +171,7 @@ class Viewport(WxPandaWindow, DirectObject): if vpType == VPFRONT: return Viewport.makeFront(parent) if vpType == VPTOP: return Viewport.makeTop(parent) if vpType == VPPERSPECTIVE: return Viewport.makePerspective(parent) - raise TypeError, "Unknown viewport type: %s" % vpType + raise TypeError("Unknown viewport type: %s" % vpType) @staticmethod def makeOrthographic(parent, name, campos): diff --git a/direct/src/wxwidgets/WxPandaWindow.py b/direct/src/wxwidgets/WxPandaWindow.py index 6d4ccd335b..79a4ebc68d 100644 --- a/direct/src/wxwidgets/WxPandaWindow.py +++ b/direct/src/wxwidgets/WxPandaWindow.py @@ -172,7 +172,7 @@ else: break if pipe.getInterfaceName() != 'OpenGL': - raise StandardError, "Couldn't get an OpenGL pipe." + raise Exception("Couldn't get an OpenGL pipe.") self.win = base.openWindow(callbackWindowDict = callbackWindowDict, pipe = pipe, gsg = gsg, type = 'onscreen') self.hasCapture = False diff --git a/makepanda/makepanda.py b/makepanda/makepanda.py index 46554539d7..71845db7b8 100755 --- a/makepanda/makepanda.py +++ b/makepanda/makepanda.py @@ -2621,7 +2621,26 @@ CreatePandaVersionFiles() ########################################################################################## if (PkgSkip("DIRECT")==0): - CopyPythonTree(GetOutputDir() + '/direct', 'direct/src', lib2to3_fixers=['all']) + fixers = [ + 'apply', + 'callable', + 'dict', + 'except', + 'execfile', + 'import', + 'imports', + 'long', + 'metaclass', + 'next', + 'numliterals', + 'print', + 'types', + 'unicode', + 'xrange', + 'xreadlines', + ] + + CopyPythonTree(GetOutputDir() + '/direct', 'direct/src', lib2to3_fixers=fixers, threads=THREADCOUNT) ConditionalWriteFile(GetOutputDir() + '/direct/__init__.py', "") # This file used to be copied, but would nowadays cause conflicts. diff --git a/makepanda/makepandacore.py b/makepanda/makepandacore.py index f395693c3f..05b6053053 100644 --- a/makepanda/makepandacore.py +++ b/makepanda/makepandacore.py @@ -2640,18 +2640,25 @@ def CopyTree(dstdir, srcdir, omitVCS=True): if omitVCS: DeleteVCS(dstdir) -def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[]): +def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[], threads=0): if (not os.path.isdir(dstdir)): os.mkdir(dstdir) lib2to3 = None + lib2to3_args = ['-w', '-n', '--no-diffs'] + if len(lib2to3_fixers) > 0 and sys.version_info >= (3, 0): from lib2to3.main import main as lib2to3 - lib2to3_args = ['-w', '-n', '--no-diffs', '-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma'] - if lib2to3_fixers != ['all']: + + if lib2to3_fixers == ['all']: + lib2to3_args += ['-x', 'buffer', '-x', 'idioms', '-x', 'set_literal', '-x', 'ws_comma'] + else: for fixer in lib2to3_fixers: lib2to3_args += ['-f', fixer] + if threads: + lib2to3_args += ['-j', str(threads)] + exclude_files = set(VCS_FILES) exclude_files.add('panda3d.py') @@ -2667,20 +2674,23 @@ def CopyPythonTree(dstdir, srcdir, lib2to3_fixers=[]): if ext == '.py' and not entry.endswith('-extensions.py'): refactor.append((dstpth, srcpth)) + lib2to3_args.append(dstpth) else: JustBuilt([dstpth], [srcpth]) elif entry not in VCS_DIRS: - CopyPythonTree(dstpth, srcpth, lib2to3_fixers) + CopyPythonTree(dstpth, srcpth, lib2to3_fixers, threads=threads) - for dstpth, srcpth in refactor: - if lib2to3 is not None: - ret = lib2to3("lib2to3.fixes", lib2to3_args + [dstpth]) - if ret != 0: + if refactor and lib2to3 is not None: + ret = lib2to3("lib2to3.fixes", lib2to3_args) + + if ret != 0: + for dstpth, srcpth in refactor: os.remove(dstpth) exit("Error in lib2to3.") - JustBuilt([dstpth], [srcpth]) - + else: + for dstpth, srcpth in refactor: + JustBuilt([dstpth], [srcpth]) ######################################################################## ##