Author: pfg Date: Mon Dec 10 15:39:30 2012 New Revision: 1419529 URL: http://svn.apache.org/viewvc?rev=1419529&view=rev Log: Python3: Add some more python 2to3 compatibility and cleanups.
Partially inspired by hanya's work. Modified: openoffice/trunk/main/pyuno/source/module/uno.py openoffice/trunk/main/scripting/source/pyprov/officehelper.py openoffice/trunk/main/scripting/source/pyprov/pythonscript.py Modified: openoffice/trunk/main/pyuno/source/module/uno.py URL: http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/uno.py?rev=1419529&r1=1419528&r2=1419529&view=diff ============================================================================== --- openoffice/trunk/main/pyuno/source/module/uno.py (original) +++ openoffice/trunk/main/pyuno/source/module/uno.py Mon Dec 10 15:39:30 2012 @@ -21,13 +21,23 @@ import sys import pyuno -import __builtin__ + +try: + import __builtin__ as builtin +except ImportError: + import builtins + +try: + unicode +except NameError: + unicode = str + import socket # since on Windows sal3.dll no longer calls WSAStartup # all functions and variables starting with a underscore (_) must be considered private # and can be changed at any time. Don't use them _g_ctx = pyuno.getComponentContext( ) -_g_delegatee = __builtin__.__dict__["__import__"] +_g_delegatee = builtin.__dict__["__import__"] def getComponentContext(): """ returns the UNO component context, that was used to initialize the python runtime. @@ -171,20 +181,6 @@ class Char: return self.value == that.value return False -# Suggested by Christian, but still some open problems which need to be solved first -# -#class ByteSequence(str): -# -# def __repr__(self): -# return "<ByteSequence instance %s>" % str.__repr__(self) - - # for a little bit compatibility; setting value is not possible as - # strings are immutable -# def _get_value(self): -# return self -# -# value = property(_get_value) - class ByteSequence: def __init__(self, value): if isinstance(value, str): @@ -286,16 +282,7 @@ def _uno_import( name, *optargs, **kwarg return mod # hook into the __import__ chain -__builtin__.__dict__["__import__"] = _uno_import - -# private function, don't use -def _impl_extractName(name): - r = list(range(len(name)-1,0,-1)) - for i in r: - if name[i] == ".": - name = name[i+1:len(name)] - break - return name +builtin.__dict__["__import__"] = _uno_import # private, referenced from the pyuno shared library def _uno_struct__init__(self,*args): @@ -306,11 +293,11 @@ def _uno_struct__init__(self,*args): # private, referenced from the pyuno shared library def _uno_struct__getattr__(self,name): - return __builtin__.getattr(self.__dict__["value"],name) + return builtin.getattr(self.__dict__["value"],name) # private, referenced from the pyuno shared library def _uno_struct__setattr__(self,name,value): - return __builtin__.setattr(self.__dict__["value"],name,value) + return builtin.setattr(self.__dict__["value"],name,value) # private, referenced from the pyuno shared library def _uno_struct__repr__(self): Modified: openoffice/trunk/main/scripting/source/pyprov/officehelper.py URL: http://svn.apache.org/viewvc/openoffice/trunk/main/scripting/source/pyprov/officehelper.py?rev=1419529&r1=1419528&r2=1419529&view=diff ============================================================================== --- openoffice/trunk/main/scripting/source/pyprov/officehelper.py (original) +++ openoffice/trunk/main/scripting/source/pyprov/officehelper.py Mon Dec 10 15:39:30 2012 @@ -81,7 +81,7 @@ def bootstrap(): except BootstrapException: raise - except Exception, e: # Any other exception + except Exception as e: # Any other exception raise BootstrapException("Caught exception " + str(e), None) return xContext Modified: openoffice/trunk/main/scripting/source/pyprov/pythonscript.py URL: http://svn.apache.org/viewvc/openoffice/trunk/main/scripting/source/pyprov/pythonscript.py?rev=1419529&r1=1419528&r2=1419529&view=diff ============================================================================== --- openoffice/trunk/main/scripting/source/pyprov/pythonscript.py (original) +++ openoffice/trunk/main/scripting/source/pyprov/pythonscript.py Mon Dec 10 15:39:30 2012 @@ -28,6 +28,11 @@ import imp import time import ast +try: + unicode +except NameError: + unicode = str + class LogLevel: NONE = 0 ERROR = 1 @@ -69,8 +74,8 @@ def getLogTarget(): if len( userInstallation ) > 0: systemPath = uno.fileUrlToSystemPath( userInstallation + "/Scripts/python/log.txt" ) ret = file( systemPath , "a" ) - except Exception,e: - print "Exception during creation of pythonscript logfile: "+ lastException2String() + "\n, delagating log to stdout\n" + except Exception as e: + print("Exception during creation of pythonscript logfile: "+ lastException2String() + "\n, delagating log to stdout\n") return ret class Logger(LogLevel): @@ -102,8 +107,8 @@ class Logger(LogLevel): encfile(msg) + "\n" ) self.target.flush() - except Exception,e: - print "Error during writing to stdout: " +lastException2String() + "\n" + except Exception as e: + print("Error during writing to stdout: " +lastException2String() + "\n") log = Logger( getLogTarget() ) @@ -202,10 +207,10 @@ class MyUriHelper: ret = self.m_baseUri + "/" + myUri.getName().replace( "|", "/" ) log.debug( "converting scriptURI="+scriptURI + " to storageURI=" + ret ) return ret - except UnoException, e: + except UnoException as e: log.error( "error during converting scriptURI="+scriptURI + ": " + e.Message) raise RuntimeException( "pythonscript:scriptURI2StorageUri: " +e.getMessage(), None ) - except Exception, e: + except Exception as e: log.error( "error during converting scriptURI="+scriptURI + ": " + str(e)) raise RuntimeException( "pythonscript:scriptURI2StorageUri: " + str(e), None ) @@ -320,7 +325,7 @@ class ProviderContext: def removePackageByUrl( self, url ): - items = self.mapPackageName2Path.items() + items = list(self.mapPackageName2Path.items()) for i in items: if url in i[1].pathes: self.mapPackageName2Path.pop(i[0]) @@ -330,7 +335,7 @@ class ProviderContext: packageName = self.getPackageNameFromUrl( url ) transientPart = self.getTransientPartFromUrl( url ) log.debug( "addPackageByUrl : " + packageName + ", " + transientPart + "("+url+")" + ", rootUrl="+self.rootUrl ) - if self.mapPackageName2Path.has_key( packageName ): + if packageName in self.mapPackageName2Path: package = self.mapPackageName2Path[ packageName ] package.pathes = package.pathes + (url, ) else: @@ -338,7 +343,7 @@ class ProviderContext: self.mapPackageName2Path[ packageName ] = package def isUrlInPackage( self, url ): - values = self.mapPackageName2Path.values() + values = list(self.mapPackageName2Path.values()) for i in values: # print "checking " + url + " in " + str(i.pathes) if url in i.pathes: @@ -432,7 +437,7 @@ class ProviderContext: code = compile( src, encfile(uno.fileUrlToSystemPath( url ) ), "exec" ) else: code = compile( src, url, "exec" ) - exec code in entry.module.__dict__ + exec(code, entry.module.__dict__) entry.module.__file__ = url self.modules[ url ] = entry log.debug( "mapped " + url + " to " + str( entry.module ) ) @@ -475,7 +480,7 @@ class ScriptBrowseNode( unohelper.Base, ret = not self.provCtx.sfa.isReadOnly( self.uri ) log.debug( "ScriptBrowseNode.getPropertyValue called for " + name + ", returning " + str(ret) ) - except Exception,e: + except Exception as e: log.error( "ScriptBrowseNode.getPropertyValue error " + lastException2String()) raise @@ -520,10 +525,10 @@ class ScriptBrowseNode( unohelper.Base, code = ensureSourceState( code ) mod = imp.new_module("ooo_script_framework") mod.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = self.provCtx.scriptContext - exec code in mod.__dict__ + exec(code, mod.__dict__) values = mod.__dict__.get( CALLABLE_CONTAINER_NAME , None ) if not values: - values = mod.__dict__.values() + values = list(mod.__dict__.values()) for i in values: if isScript( i ): @@ -544,7 +549,7 @@ class ScriptBrowseNode( unohelper.Base, # log.debug("Save is not implemented yet") # text = self.editor.getControl("EditorTextField").getText() # log.debug("Would save: " + text) - except Exception,e: + except Exception as e: # TODO: add an error box here ! log.error( lastException2String() ) @@ -585,7 +590,7 @@ class FileBrowseNode( unohelper.Base, XB self.provCtx, self.uri, self.name, i )) ret = tuple( scriptNodeList ) log.debug( "returning " +str(len(ret)) + " ScriptChildNodes on " + self.uri ) - except Exception, e: + except Exception as e: text = lastException2String() log.error( "Error while evaluating " + self.uri + ":" + text ) raise @@ -594,7 +599,7 @@ class FileBrowseNode( unohelper.Base, XB def hasChildNodes(self): try: return len(self.getChildNodes()) > 0 - except Exception, e: + except Exception as e: return False def getType( self): @@ -625,7 +630,7 @@ class DirBrowseNode( unohelper.Base, XBr log.debug( "adding DirBrowseNode " + i ) browseNodeList.append( DirBrowseNode( self.provCtx, i[i.rfind("/")+1:len(i)],i)) return tuple( browseNodeList ) - except Exception, e: + except Exception as e: text = lastException2String() log.error( "DirBrowseNode error: " + str(e) + " while evaluating " + self.rootUrl) log.error( text) @@ -697,7 +702,7 @@ def getPathesFromPackage( rootUrl, sfa ) if not isPyFileInPath( sfa, i ): handler.urlList.remove(i) ret = tuple( handler.urlList ) - except UnoException, e: + except UnoException as e: text = lastException2String() log.debug( "getPathesFromPackage " + fileUrl + " Exception: " +text ) pass @@ -765,7 +770,7 @@ def getModelFromDocUrl(ctx, url): try: ret = content.execute(c, 0, env) doc = ret.getObject(1, None) - except Exception, e: + except Exception as e: log.isErrorLevel() and log.error("getModelFromDocUrl: %s" % url) return doc @@ -818,7 +823,7 @@ class PackageBrowseNode( unohelper.Base, return self.name def getChildNodes( self ): - items = self.provCtx.mapPackageName2Path.items() + items = list(self.provCtx.mapPackageName2Path.items()) browseNodeList = [] for i in items: if len( i[1].pathes ) == 1: @@ -851,7 +856,7 @@ class PythonScript( unohelper.Base, XScr log.debug( "PythonScript.invoke " + str( args ) ) try: ret = self.func( *args ) - except UnoException,e: + except UnoException as e: # UNO Exception continue to fly ... text = lastException2String() complete = "Error during invoking function " + \ @@ -864,7 +869,7 @@ class PythonScript( unohelper.Base, XScr # this is really bad for most users. e.Message = e.Message + " (" + complete + ")" raise - except Exception,e: + except Exception as e: # General python exception are converted to uno RuntimeException text = lastException2String() complete = "Error during invoking function " + \ @@ -911,7 +916,7 @@ class PythonScriptProvider( unohelper.Ba "com.sun.star.frame.TransientDocumentsDocumentContentFactory", ctx).createDocumentContent(doc) storageType = content.getIdentifier().getContentIdentifier() - except Exception, e: + except Exception as e: text = lastException2String() log.error( text ) @@ -941,7 +946,7 @@ class PythonScriptProvider( unohelper.Ba else: self.dirBrowseNode = DirBrowseNode( self.provCtx, LANGUAGENAME, rootUrl ) - except Exception, e: + except Exception as e: text = lastException2String() log.debug( "PythonScriptProvider could not be instantiated because of : " + text ) raise e @@ -980,7 +985,7 @@ class PythonScriptProvider( unohelper.Ba log.debug( "got func " + str( func ) ) return PythonScript( func, mod ) - except Exception, e: + except Exception as e: text = lastException2String() log.error( text ) raise ScriptFrameworkErrorException( text, self, scriptUri, LANGUAGENAME, 0 ) @@ -1012,7 +1017,7 @@ class PythonScriptProvider( unohelper.Ba ret = self.provCtx.isUrlInPackage( uri ) log.debug( "hasByName " + uri + " " +str( ret ) ) return ret - except Exception, e: + except Exception as e: text = lastException2String() log.debug( "Error in hasByName:" + text ) return False