Kaydet (Commit) 2f2c34da authored tarafından Pedro Giffuni's avatar Pedro Giffuni

Improve portability of pyuno python scripts.

Proper indentation is critical in Python: the
reindent.py script made some cleanups.

Running the 2to3 script with specific options to
disabling the next, unicode, and imports fixers
further enhance portability.

pyuno is not yet Python 3 ready but these
semiautomatic changes make things much easier.
üst 3cfc2469
...@@ -43,12 +43,12 @@ def main(): ...@@ -43,12 +43,12 @@ def main():
rowset.execute(); rowset.execute();
print "Identifier\tAuthor" print("Identifier\tAuthor")
id = rowset.findColumn( "IDENTIFIER" ) id = rowset.findColumn( "IDENTIFIER" )
author = rowset.findColumn( "AUTHOR" ) author = rowset.findColumn( "AUTHOR" )
while rowset.next(): while rowset.next():
print rowset.getString( id ) + "\t" + repr( rowset.getString( author ) ) print(rowset.getString( id ) + "\t" + repr( rowset.getString( author ) ))
rowset.dispose(); rowset.dispose();
......
...@@ -61,7 +61,7 @@ def main(): ...@@ -61,7 +61,7 @@ def main():
if o == "--html": if o == "--html":
filterName = "HTML (StarWriter)" filterName = "HTML (StarWriter)"
print filterName print(filterName)
if not len( args ): if not len( args ):
usage() usage()
sys.exit() sys.exit()
...@@ -90,19 +90,19 @@ def main(): ...@@ -90,19 +90,19 @@ def main():
raise UnoException( "Couldn't open stream for unknown reason", None ) raise UnoException( "Couldn't open stream for unknown reason", None )
doc.storeToURL("private:stream",outProps) doc.storeToURL("private:stream",outProps)
except IOException, e: except IOException as e:
sys.stderr.write( "Error during conversion: " + e.Message + "\n" ) sys.stderr.write( "Error during conversion: " + e.Message + "\n" )
retVal = 1 retVal = 1
except UnoException, e: except UnoException as e:
sys.stderr.write( "Error ("+repr(e.__class__)+") during conversion:" + e.Message + "\n" ) sys.stderr.write( "Error ("+repr(e.__class__)+") during conversion:" + e.Message + "\n" )
retVal = 1 retVal = 1
if doc: if doc:
doc.dispose() doc.dispose()
except UnoException, e: except UnoException as e:
sys.stderr.write( "Error ("+repr(e.__class__)+") :" + e.Message + "\n" ) sys.stderr.write( "Error ("+repr(e.__class__)+") :" + e.Message + "\n" )
retVal = 1 retVal = 1
except getopt.GetoptError,e: except getopt.GetoptError as e:
sys.stderr.write( str(e) + "\n" ) sys.stderr.write( str(e) + "\n" )
usage() usage()
retVal = 1 retVal = 1
......
...@@ -31,4 +31,3 @@ remoteSmgr = remoteContext.ServiceManager ...@@ -31,4 +31,3 @@ remoteSmgr = remoteContext.ServiceManager
pyComp = remoteSmgr.createInstanceWithContext( "org.openoffice.demo.SWriter" , remoteContext ) pyComp = remoteSmgr.createInstanceWithContext( "org.openoffice.demo.SWriter" , remoteContext )
pyComp.run( (), ) pyComp.run( (), )
...@@ -43,16 +43,16 @@ g_loadedComponents = {} ...@@ -43,16 +43,16 @@ g_loadedComponents = {}
def checkForPythonPathBesideComponent( url ): def checkForPythonPathBesideComponent( url ):
path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" );
if DEBUG == 1: if DEBUG == 1:
print "checking for existence of " + encfile( path ) print("checking for existence of " + encfile( path ))
if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path:
if DEBUG == 1: if DEBUG == 1:
print "adding " + encfile( path ) + " to sys.path" print("adding " + encfile( path ) + " to sys.path")
sys.path.append( path ) sys.path.append( path )
path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); path = unohelper.fileUrlToSystemPath( url+"/pythonpath" );
if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path:
if DEBUG == 1: if DEBUG == 1:
print "adding " + encfile( path ) + " to sys.path" print("adding " + encfile( path ) + " to sys.path")
sys.path.append( path ) sys.path.append( path )
def encfile(uni): def encfile(uni):
...@@ -61,12 +61,12 @@ def encfile(uni): ...@@ -61,12 +61,12 @@ def encfile(uni):
class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
def __init__(self, ctx ): def __init__(self, ctx ):
if DEBUG: if DEBUG:
print "pythonloader.Loader ctor" print("pythonloader.Loader ctor")
self.ctx = ctx self.ctx = ctx
def getModuleFromUrl( self, url ): def getModuleFromUrl( self, url ):
if DEBUG: if DEBUG:
print "pythonloader: interpreting url " +url print("pythonloader: interpreting url " +url)
protocol, dependent = splitUrl( url ) protocol, dependent = splitUrl( url )
if "vnd.sun.star.expand" == protocol: if "vnd.sun.star.expand" == protocol:
exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" )
...@@ -74,7 +74,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): ...@@ -74,7 +74,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
protocol,dependent = splitUrl( url ) protocol,dependent = splitUrl( url )
if DEBUG: if DEBUG:
print "pythonloader: after expansion " +protocol +":" + dependent print("pythonloader: after expansion " +protocol +":" + dependent)
try: try:
if "file" == protocol: if "file" == protocol:
...@@ -98,7 +98,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): ...@@ -98,7 +98,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
# compile and execute the module # compile and execute the module
codeobject = compile( src, encfile(filename), "exec" ) codeobject = compile( src, encfile(filename), "exec" )
exec codeobject in mod.__dict__ exec(codeobject, mod.__dict__)
mod.__file__ = encfile(filename) mod.__file__ = encfile(filename)
g_loadedComponents[url] = mod g_loadedComponents[url] = mod
return mod return mod
...@@ -107,13 +107,13 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): ...@@ -107,13 +107,13 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
else: else:
raise RuntimeException( "PythonLoader: Unknown protocol " + raise RuntimeException( "PythonLoader: Unknown protocol " +
protocol + " in url " +url, self ) protocol + " in url " +url, self )
except ImportError, e: except ImportError as e:
raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None)
return None return None
def activate( self, implementationName, dummy, locationUrl, regKey ): def activate( self, implementationName, dummy, locationUrl, regKey ):
if DEBUG: if DEBUG:
print "pythonloader.Loader.activate" print("pythonloader.Loader.activate")
mod = self.getModuleFromUrl( locationUrl ) mod = self.getModuleFromUrl( locationUrl )
implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) implHelper = mod.__dict__.get( "g_ImplementationHelper" , None )
...@@ -124,7 +124,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): ...@@ -124,7 +124,7 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
def writeRegistryInfo( self, regKey, dummy, locationUrl ): def writeRegistryInfo( self, regKey, dummy, locationUrl ):
if DEBUG: if DEBUG:
print "pythonloader.Loader.writeRegistryInfo" print("pythonloader.Loader.writeRegistryInfo")
mod = self.getModuleFromUrl( locationUrl ) mod = self.getModuleFromUrl( locationUrl )
implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) implHelper = mod.__dict__.get( "g_ImplementationHelper" , None )
...@@ -141,5 +141,3 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): ...@@ -141,5 +141,3 @@ class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ):
def getSupportedServiceNames( self ): def getSupportedServiceNames( self ):
return g_supportedServices return g_supportedServices
...@@ -178,7 +178,7 @@ class Char: ...@@ -178,7 +178,7 @@ class Char:
# def __repr__(self): # def __repr__(self):
# return "<ByteSequence instance %s>" % str.__repr__(self) # return "<ByteSequence instance %s>" % str.__repr__(self)
# for a little bit compatitbility; setting value is not possible as # for a little bit compatibility; setting value is not possible as
# strings are immutable # strings are immutable
# def _get_value(self): # def _get_value(self):
# return self # return self
...@@ -254,7 +254,7 @@ def _uno_import( name, *optargs, **kwargs ): ...@@ -254,7 +254,7 @@ def _uno_import( name, *optargs, **kwargs ):
mod = None mod = None
d = sys.modules d = sys.modules
for x in modnames: for x in modnames:
if d.has_key(x): if x in d:
mod = d[x] mod = d[x]
else: else:
mod = pyuno.__class__(x) # How to create a module ?? mod = pyuno.__class__(x) # How to create a module ??
...@@ -262,25 +262,25 @@ def _uno_import( name, *optargs, **kwargs ): ...@@ -262,25 +262,25 @@ def _uno_import( name, *optargs, **kwargs ):
RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" ) RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
for x in fromlist: for x in fromlist:
if not d.has_key(x): if x not in d:
if x.startswith( "typeOf" ): if x.startswith( "typeOf" ):
try: try:
d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
except RuntimeException,e: except RuntimeException as e:
raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
else: else:
try: try:
# check for structs, exceptions or interfaces # check for structs, exceptions or interfaces
d[x] = pyuno.getClass( name + "." + x ) d[x] = pyuno.getClass( name + "." + x )
except RuntimeException,e: except RuntimeException as e:
# check for enums # check for enums
try: try:
d[x] = Enum( name , x ) d[x] = Enum( name , x )
except RuntimeException,e2: except RuntimeException as e2:
# check for constants # check for constants
try: try:
d[x] = getConstantByName( name + "." + x ) d[x] = getConstantByName( name + "." + x )
except RuntimeException,e3: except RuntimeException as e3:
# no known uno type ! # no known uno type !
raise ImportError( "type "+ name + "." +x + " is unknown" ) raise ImportError( "type "+ name + "." +x + " is unknown" )
return mod return mod
...@@ -290,7 +290,7 @@ __builtin__.__dict__["__import__"] = _uno_import ...@@ -290,7 +290,7 @@ __builtin__.__dict__["__import__"] = _uno_import
# private function, don't use # private function, don't use
def _impl_extractName(name): def _impl_extractName(name):
r = range (len(name)-1,0,-1) r = list(range(len(name)-1,0,-1))
for i in r: for i in r:
if name[i] == ".": if name[i] == ".":
name = name[i+1:len(name)] name = name[i+1:len(name)]
...@@ -330,7 +330,7 @@ def _uno_extract_printable_stacktrace( trace ): ...@@ -330,7 +330,7 @@ def _uno_extract_printable_stacktrace( trace ):
mod = None mod = None
try: try:
mod = __import__("traceback") mod = __import__("traceback")
except ImportError,e: except ImportError as e:
pass pass
ret = "" ret = ""
if mod: if mod:
......
...@@ -138,7 +138,7 @@ class ImplementationHelper: ...@@ -138,7 +138,7 @@ class ImplementationHelper:
self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames)
def writeRegistryInfo( self, regKey, smgr ): def writeRegistryInfo( self, regKey, smgr ):
for i in self.impls.items(): for i in list(self.impls.items()):
keyName = "/"+ i[0] + "/UNO/SERVICES" keyName = "/"+ i[0] + "/UNO/SERVICES"
key = regKey.createKey( keyName ) key = regKey.createKey( keyName )
for serviceName in i[1].serviceNames: for serviceName in i[1].serviceNames:
...@@ -225,7 +225,7 @@ def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, ...@@ -225,7 +225,7 @@ def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls,
_g_typeTable = {} _g_typeTable = {}
def _unohelper_getHandle( self): def _unohelper_getHandle( self):
ret = None ret = None
if _g_typeTable.has_key( self.__class__ ): if self.__class__ in _g_typeTable:
ret = _g_typeTable[self.__class__] ret = _g_typeTable[self.__class__]
else: else:
names = {} names = {}
...@@ -239,7 +239,7 @@ def _unohelper_getHandle( self): ...@@ -239,7 +239,7 @@ def _unohelper_getHandle( self):
# the "else if", because we only need the most derived interface # the "else if", because we only need the most derived interface
traverse = traverse + list(bases)# traverse = traverse + list(bases)#
lst = names.keys() lst = list(names.keys())
types = [] types = []
for x in lst: for x in lst:
t = uno.getTypeByName( x ) t = uno.getTypeByName( x )
...@@ -295,4 +295,3 @@ class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ): ...@@ -295,4 +295,3 @@ class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ):
def createInstanceWithArgumentsAndContext( self, args, context ): def createInstanceWithArgumentsAndContext( self, args, context ):
return self.clazz( context, *args ) return self.clazz( context, *args )
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment