StandardError -> Exception, other 2to3 changes, threaded 2to3

This commit is contained in:
rdb 2016-03-25 17:06:50 +01:00
parent 6334f2511d
commit 54fa31ba17
43 changed files with 211 additions and 172 deletions

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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 + "<br>\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 = "<h1>List of Methods - Panda " + pversion + "</h1>\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)

View File

@ -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"

View File

@ -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"

View File

@ -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

View File

@ -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.

View File

@ -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

View File

@ -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'):

View File

@ -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'])

View File

@ -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')):

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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])

View File

@ -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)

View File

@ -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. """

View File

@ -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)

View File

@ -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)

View File

@ -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())

View File

@ -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)

View File

@ -123,7 +123,7 @@ class Audio3DManager:
Default: VBase3(0, 0, 0)
"""
if not isinstance(velocity, VBase3):
raise TypeError, "Invalid argument 1, expected <VBase3>"
raise TypeError("Invalid argument 1, expected <VBase3>")
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 <VBase3>"
raise TypeError("Invalid argument 0, expected <VBase3>")
self.listener_vel=velocity
def setListenerVelocityAuto(self):

View File

@ -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.

View File

@ -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')

View File

@ -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

View File

@ -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):

View File

@ -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()

View File

@ -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)

View File

@ -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):

View File

@ -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()

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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):

View File

@ -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:

View File

@ -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):

View File

@ -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

View File

@ -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.

View File

@ -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])
########################################################################
##