Kaydet (Commit) 57fadc88 authored tarafından Pedro Giffuni's avatar Pedro Giffuni

#i121496# - [PyUNO] Python3 support

Add initial python 3 compatibility to native scripts now that
pyuno supports python3.

This is the result of running the python 2to3 script with
conservative settings.

Still more porting work may be required and any regression
with the default Python 2.7.3 should be considered a bug.
üst 1a699e62
......@@ -23,8 +23,8 @@
class _const:
class ConstError(TypeError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s)"%name
if name in self.__dict__:
raise self.ConstError("Can't rebind const(%s)"%name)
self.__dict__[name] = value
import sys
......
......@@ -123,7 +123,7 @@ class AbstractL10nTool:
try:
shutil.copy(inputfilename, outputfilename)
except IOError:
print "ERROR: Can not copy file '" + inputfilename + "' to " + "'" + outputfilename + "'"
print("ERROR: Can not copy file '" + inputfilename + "' to " + "'" + outputfilename + "'")
sys.exit(-1)
def extract(self):
......@@ -131,7 +131,7 @@ class AbstractL10nTool:
f = open(self._options.outputfile, "w+")
f.write(self.extract_file(self._options.inputfile))
except IOError:
print "ERROR: Can not write file " + self._options.outputfile
print("ERROR: Can not write file " + self._options.outputfile)
else:
f.close()
......@@ -173,7 +173,7 @@ class AbstractL10nTool:
dir = filename[:filename.rfind('/')]
if os.path.exists(dir):
if os.path.isfile(dir):
print "ERROR: There is a file '"+dir+"' where I want create a directory"
print("ERROR: There is a file '"+dir+"' where I want create a directory")
sys.exit(-1)
else:
return
......@@ -181,7 +181,7 @@ class AbstractL10nTool:
try:
os.makedirs(dir)
except IOError:
print "Error: Can not create dir " + dir
print("Error: Can not create dir " + dir)
sys.exit(-1)
def test_options(self):
......@@ -191,7 +191,7 @@ class AbstractL10nTool:
( is_valid(opt.inputfile) and (( is_valid(opt.path_prefix) and is_valid(opt.path_postfix) ) or is_valid(opt.outputfile)) and \
( ( is_valid(opt.input_sdf_file) and ( is_valid(opt.outputfile) or ( is_valid(opt.path_prefix) and is_valid(opt.path_postfix) ) or \
( is_valid(opt.inputfile) and is_valid(opt.outputFile)) ))))
print "Strange options ..."
print("Strange options ...")
sys.exit( -1 )
def read_inputfile_list(self):
......@@ -201,7 +201,7 @@ class AbstractL10nTool:
f = open(self._options.inputfile[1:], "r")
lines = [line.strip('\n') for line in f.readlines()]
except IOError:
print "ERROR: Can not read file list " + self._options.inputfile[2:]
print("ERROR: Can not read file list " + self._options.inputfile[2:])
sys.exit(-1)
else:
f.close()
......
......@@ -38,7 +38,7 @@ class PseudoSet:
tmplist.extend(other)
return PseudoSet(self._remove_dupes(tmplist))
else:
print "__or__(None)"
print("__or__(None)")
def __sub__(self,other):
tmplist = []
......@@ -46,7 +46,7 @@ class PseudoSet:
tmplist.extend(self._list)
[tmplist.remove(key) for key in other if key in tmplist]
else:
print "__sub__(none)"
print("__sub__(none)")
return PseudoSet(tmplist)
def __and__(self, other):
......@@ -55,13 +55,13 @@ class PseudoSet:
[tmplist.append(key) for key in self._list if key in other]
return PseudoSet(tmplist)
else:
print "__and__(None)"
print("__and__(None)")
def __iter__(self):
return self._list.__iter__()
def __items__(self):
return self._list.items()
return list(self._list.items())
def __keys__(self):
return keys(self._list)
......@@ -70,7 +70,7 @@ class PseudoSet:
tmpdict = {}
for key in list:
tmpdict[key] = 1
return tmpdict.keys()
return list(tmpdict.keys())
# incomplete OrderedDict() class implementation
class PseudoOrderedDict(dict):
......@@ -79,7 +79,7 @@ class PseudoOrderedDict(dict):
def __init__(self, defaults={}):
dict.__init__(self)
for n,v in defaults.items():
for n,v in list(defaults.items()):
self[n] = v
def __setitem__(self, key, value):
......@@ -105,10 +105,10 @@ class PseudoOrderedDict(dict):
def iteritems(self):
#return self._valuelist
return zip(self._keylist, self._valuelist)
return list(zip(self._keylist, self._valuelist))
def items(self):
return zip(self._keylist,self._valuelist)
return list(zip(self._keylist,self._valuelist))
def __keys__(self):
return self._keylist
......@@ -140,23 +140,23 @@ def _testdriver_set():
list1.append("e")
if "a" in list:
print "YEAH!"
print("YEAH!")
a = PseudoSet(list)
b = PseudoSet(list1)
print "a="+str(a)
print "b="+str(b)
print "a|b=" + str(a|b)
print "a="+str(a)
print "b="+str(b)
print "a&b=" + str(a&b)
print "a="+str(a)
print "b="+str(b)
print "a-b" + str(a-b)
print("a="+str(a))
print("b="+str(b))
print("a|b=" + str(a|b))
print("a="+str(a))
print("b="+str(b))
print("a&b=" + str(a&b))
print("a="+str(a))
print("b="+str(b))
print("a-b" + str(a-b))
for key in a:
print key
print(key)
def _testdriver_dict():
d = PseudoOrderedDict()
......@@ -167,12 +167,12 @@ def _testdriver_dict():
d["e"] = 5
d["f"] = 6
print "a="+str(d["a"])
print "e="+str(d["e"])
for key,value in d.iteritems():
print "d["+key+"]="+str(d[key])
print "key="+str(key)+" value="+str(value)
print("a="+str(d["a"]))
print("e="+str(d["e"]))
for key,value in d.items():
print("d["+key+"]="+str(d[key]))
print("key="+str(key)+" value="+str(value))
print "keys="+str(d.keys())
print("keys="+str(list(d.keys())))
#_testdriver_dict()
......@@ -31,13 +31,13 @@ class SdfData:
self._filename = filename
def __getitem__(self, key):
if self._dict.has_key(key):
if key in self._dict:
return self._dict[key]
else:
return None
def has_key(self, key):
return self._dict.has_key(key)
return key in self._dict
def __setitem__(self, key, value):
self._dict[key] = value
......@@ -50,7 +50,7 @@ class SdfData:
f = open(self._filename, "r")
lines = [line.rstrip('\n') for line in f.readlines()]
except IOError:
print "ERROR: Trying to read "+ self._filename
print("ERROR: Trying to read "+ self._filename)
raise
else:
f.close()
......@@ -63,11 +63,11 @@ class SdfData:
def write(self, filename):
try:
f = open(filename, "w+")
for value in self._dict.itervalues():
for value in self._dict.values():
#f.write( repr(value)+"\n" )
f.write(value + "\n")
except IOError:
print "ERROR: Trying to write " + filename
print("ERROR: Trying to write " + filename)
raise
else:
f.close()
......
......@@ -39,14 +39,14 @@ class Xtxex(AbstractL10nTool):
return
# merge usual lang
sdfline = self.prepare_sdf_line(inputfilename,lang)
if sdfdata.has_key(sdfline.get_id()):
if sdfline.get_id() in sdfdata:
line = sdfdata[sdfline.get_id()].text.replace("\\n", '\n')
self.make_dirs(outputfilename)
try:
f = open(outputfilename, "w+")
f.write(line)
except IOError:
print "ERROR: Can not write file " + outputfilename
print("ERROR: Can not write file " + outputfilename)
sys.exit(-1)
else:
f.close()
......@@ -62,7 +62,7 @@ class Xtxex(AbstractL10nTool):
f = open(inputfile, "r")
lines = f.readlines()
except IOError:
print "ERROR: Can not open file " + inputfile
print("ERROR: Can not open file " + inputfile)
sys.exit(-1)
else:
f.close()
......
......@@ -25,7 +25,7 @@ import sys
localeNames = {'fr': 'French', 'hu': 'Hungarian', 'de': 'German'}
def getLocaleName (code):
global localeNames
if localeNames.has_key(code):
if code in localeNames:
return localeNames[code]
else:
return "(unknown locale)"
......@@ -42,7 +42,7 @@ class LocaleData(object):
self.funcList = {}
def addKeywordMap (self, funcName, localeName, engName):
if not self.funcList.has_key(funcName):
if funcName not in self.funcList:
self.funcList[funcName] = []
self.funcList[funcName].append([localeName, engName])
......@@ -136,7 +136,7 @@ class Parser(object):
for item in buf:
sys.stdout.write(chr(item))
if linefeed:
print ''
print('')
def parse (self):
......
......@@ -211,7 +211,7 @@ class TestCase( unittest.TestCase):
wasHere = 0
try:
raise ioExc( "huhuh" , self.tobj )
except unoExc , instance:
except unoExc as instance:
wasHere = 1
self.failUnless( wasHere , "exceptiont test 1" )
......@@ -239,7 +239,7 @@ class TestCase( unittest.TestCase):
self.failUnless( 0 , "exception test 5a" )
except ioExc:
self.failUnless( 0 , "exception test 5b" )
except illegalArg, i:
except illegalArg as i:
self.failUnless( 1 == i.ArgumentPosition , "exception member test" )
self.failUnless( "foo" == i.Message , "exception member test 2 " )
wasHere = 1
......
......@@ -31,7 +31,7 @@ class DlgLayoutBuilder(object):
def addWidget (self, elem):
x, y = int(elem.getAttr('x')), int(elem.getAttr('y'))
self.rows[y] = self.rows.get (y, {})
while self.rows[y].has_key(x):
while x in self.rows[y]:
y += 1
self.rows[y] = self.rows.get (y, {})
self.rows[y][x] = elem
......
......@@ -125,4 +125,4 @@ class ExpParser(object):
def dumpTree (self):
self.jumpToRoot()
print toString(self.ptr)
print(toString(self.ptr))
......@@ -108,7 +108,7 @@ class Element(Node):
return chars
def hasAttr (self, name):
return self.attrs.has_key(name)
return name in self.attrs
def getAttr (self, name):
return self.attrs[name]
......@@ -121,7 +121,7 @@ class Element(Node):
return
def clone (self, elem):
keys = elem.attrs.keys()
keys = list(elem.attrs.keys())
for key in keys:
self.attrs[key] = elem.attrs[key]
self.rid = elem.rid
......
......@@ -31,7 +31,7 @@ class TestCase:
mcExpander.debug = True
mcExpander.expand()
tokens = mcExpander.getTokens()
print tokens
print(tokens)
@staticmethod
def simpleNoArgs ():
......@@ -79,13 +79,13 @@ class TestCase:
TestCase.run(tokens, defines)
def main ():
print "simple expansion with no arguments"
print("simple expansion with no arguments")
TestCase.simpleNoArgs()
print "simple argument expansion"
print("simple argument expansion")
TestCase.simpleArgs()
print "multi-token argument expansion"
print("multi-token argument expansion")
TestCase.multiTokenArgs()
print "nested argument expansion"
print("nested argument expansion")
TestCase.nestedTokenArgs()
if __name__ == '__main__':
......
......@@ -37,8 +37,8 @@ A macro with arguments must have its open paren immediately following
its name without any whitespace.
"""
if self.debug:
print "-"*68
print "parsing '%s'"%self.buffer
print("-"*68)
print("parsing '%s'"%self.buffer)
i = 0
bufSize = len(self.buffer)
......@@ -105,17 +105,17 @@ character is the open paren.
def setMacro (self, name, vars, content):
if self.debug:
print "-"*68
print "name: %s"%name
print("-"*68)
print("name: %s"%name)
for var in vars:
print "var: %s"%var
print("var: %s"%var)
if len(vars) == 0:
print "no vars"
print "content: '%s'"%content
print("no vars")
print("content: '%s'"%content)
if len(content) > 0:
self.macro = Macro(name)
for i in xrange(0, len(vars)):
for i in range(0, len(vars)):
self.macro.vars[vars[i]] = i
# tokinize it using lexer.
......@@ -125,16 +125,16 @@ character is the open paren.
mclexer.tokenize()
self.macro.tokens = mclexer.getTokens()
if self.debug:
print self.macro.tokens
print(self.macro.tokens)
if not self.isValidMacro(self.macro):
self.macro = None
if self.debug:
if self.macro != None:
print "macro registered!"
print("macro registered!")
else:
print "macro not registered"
print("macro not registered")
def isValidMacro (self, macro):
......
......@@ -182,12 +182,12 @@ def dry_one_file (file_name, options):
try:
str = convert(file_name, options)
progress (" SUCCESS\n")
except Exception, e:
except Exception as e:
if options.keep_going:
progress (" FAILED\n")
else:
import traceback
print traceback.format_exc (None)
print(traceback.format_exc (None))
raise e
def post_process (s):
......
......@@ -303,14 +303,14 @@ build the syntax tree.
self.handleMacroInclude(buf)
elif command == 'ifdef':
defineName = buf.strip()
if self.defines.has_key(defineName):
if defineName in self.defines:
self.visibilityStack.append(SrcLexer.VISIBLE)
else:
self.visibilityStack.append(SrcLexer.INVISIBLE_PRE)
elif command == 'ifndef':
defineName = buf.strip()
if self.defines.has_key(defineName):
if defineName in self.defines:
self.visibilityStack.append(SrcLexer.INVISIBLE_PRE)
else:
self.visibilityStack.append(SrcLexer.VISIBLE)
......@@ -351,8 +351,8 @@ build the syntax tree.
elif command in ['error', 'pragma']:
pass
else:
print "'%s' '%s'"%(command, buf)
print self.filepath
print("'%s' '%s'"%(command, buf))
print(self.filepath)
sys.exit(0)
return i
......@@ -407,10 +407,10 @@ build the syntax tree.
progress ("%s already included\n"%headerPath)
return
if SrcLexer.headerCache.has_key(headerPath):
if headerPath in SrcLexer.headerCache:
if self.debug:
progress ("%s in cache\n"%headerPath)
for key in SrcLexer.headerCache[headerPath].defines.keys():
for key in list(SrcLexer.headerCache[headerPath].defines.keys()):
self.defines[key] = SrcLexer.headerCache[headerPath].defines[key]
return
......@@ -422,7 +422,7 @@ build the syntax tree.
hdrData = HeaderData()
hdrData.tokens = mclexer.getTokens()
headerDefines = mclexer.getDefines()
for key in headerDefines.keys():
for key in list(headerDefines.keys()):
defines[key] = headerDefines[key]
hdrData.defines[key] = headerDefines[key]
......@@ -430,15 +430,15 @@ build the syntax tree.
SrcLexer.headerCache[headerPath] = hdrData
# Update the list of headers that have already been expaneded.
for key in mclexer.headerDict.keys():
for key in list(mclexer.headerDict.keys()):
self.headerDict[key] = True
if self.debug:
progress ("defines found in header %s:\n"%headerSub)
for key in defines.keys():
for key in list(defines.keys()):
progress (" '%s'\n"%key)
for key in defines.keys():
for key in list(defines.keys()):
self.defines[key] = defines[key]
......
......@@ -108,12 +108,12 @@ class MacroExpander(object):
def expandToken (self):
token = self.tokens[self.pos]
if not self.defines.has_key(token):
if token not in self.defines:
self.pos += 1
return
macro = self.defines[token]
nvars = len(macro.vars.keys())
nvars = len(list(macro.vars.keys()))
if nvars == 0:
# Simple expansion
self.tokens[self.pos:self.pos+1] = macro.tokens
......@@ -123,7 +123,7 @@ class MacroExpander(object):
values, lastPos = self.parseValues()
newtokens = []
for mtoken in macro.tokens:
if macro.vars.has_key(mtoken):
if mtoken in macro.vars:
# variable
pos = macro.vars[mtoken]
valtokens = values[pos]
......@@ -155,15 +155,15 @@ words, whitespace does not end a token.
tk = self.tokens[self.pos+i]
except IndexError:
progress ("error parsing values (%d)\n"%i)
for j in xrange(0, i):
print self.tokens[self.pos+j],
print ''
for j in range(0, i):
print(self.tokens[self.pos+j], end=' ')
print('')
srclexer.dumpTokens(self.tokens)
srclexer.dumpTokens(self.newtokens)
print "tokens expanded so far:"
print("tokens expanded so far:")
for tk in self.expandedTokens:
print "-"*20
print tk
print("-"*20)
print(tk)
srclexer.dumpTokens(self.defines[tk].tokens)
sys.exit(1)
if tk == '(':
......@@ -207,7 +207,7 @@ class SrcParser(object):
# Expand defined macros.
if self.debug:
progress ("-"*68+"\n")
for key in self.defines.keys():
for key in list(self.defines.keys()):
progress ("define: %s\n"%key)
self.expandMacro()
......@@ -314,7 +314,7 @@ handler.
def closeBrace (self, i):
if len(self.tokenBuf) > 0:
if self.debug:
print self.tokenBuf
print(self.tokenBuf)
raise ParseError ('')
self.elementStack.pop()
return i
......
......@@ -29,7 +29,7 @@ def grep(pattern,dirname,names):
lines = open(filename,"r").readlines()
for line in lines:
if pattern.search(line):
print filename
print(filename)
break
......
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