summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSlávek Banko <slavek.banko@axis.cz>2023-01-22 02:02:13 +0100
committerSlávek Banko <slavek.banko@axis.cz>2023-01-22 02:02:13 +0100
commit86480e58eafc1fa3486e03155ed34e02b4595a24 (patch)
tree0e8f64c4003ea558e946b7a3347688904b451635
parent135d005014a1e85295af4e379f026a361537ae5f (diff)
downloadkoffice-86480e58.tar.gz
koffice-86480e58.zip
Drop python2 support in scripts.
Signed-off-by: Slávek Banko <slavek.banko@axis.cz>
-rwxr-xr-xchalk/core/createdcop.py4
-rw-r--r--chalk/doc/scripts/dcop.py6
-rw-r--r--chalk/plugins/viewplugins/scripting/samples/python/invert.py4
-rw-r--r--chalk/plugins/viewplugins/scripting/samples/python/reshapehisto.py20
-rw-r--r--kexi/plugins/scripting/scripts/copycenter/CopyCenter.py66
-rw-r--r--kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py52
-rw-r--r--kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginQtSQL.py56
-rw-r--r--kexi/plugins/scripting/scripts/exportxhtml/ExportXHTML.py16
-rwxr-xr-xkexi/plugins/scripting/scripts/importxhtml/ImportXHTML.py36
-rwxr-xr-xkexi/plugins/scripting/scripts/projectdocumentor/ProjectDocumentor.py18
-rwxr-xr-xkexi/plugins/scripting/scripts/python/kexiapp/__init__.py2
-rwxr-xr-xkspread/plugins/scripting/scripts/exporthtml/ExportHtml.py9
-rwxr-xr-xkspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py118
-rw-r--r--lib/kformula/prototype/gensymbolfontmap.py48
-rwxr-xr-xlib/kformula/prototype/unicode.py18
-rwxr-xr-xlib/kformula/scripts/bycodes.py10
-rwxr-xr-xlib/kformula/scripts/bynames.py22
-rwxr-xr-xlib/kformula/scripts/oper-dict.py38
-rw-r--r--lib/kross/python/scripts/RestrictedPython/Eval.py6
-rw-r--r--lib/kross/python/scripts/RestrictedPython/Guards.py2
-rw-r--r--lib/kross/python/scripts/RestrictedPython/Limits.py12
-rw-r--r--lib/kross/python/scripts/RestrictedPython/MutatingWalker.py2
-rw-r--r--lib/kross/python/scripts/RestrictedPython/RCompile.py4
-rw-r--r--lib/kross/python/scripts/RestrictedPython/RestrictionMutator.py2
-rwxr-xr-xlib/kross/python/scripts/gui.py96
-rw-r--r--lib/kross/test/testcase.py88
-rw-r--r--lib/kross/test/testgui.py42
-rw-r--r--lib/kross/test/testkexidb.py52
-rwxr-xr-xlib/kross/test/testperformance.py4
29 files changed, 428 insertions, 425 deletions
diff --git a/chalk/core/createdcop.py b/chalk/core/createdcop.py
index 337d90761..f51b39686 100755
--- a/chalk/core/createdcop.py
+++ b/chalk/core/createdcop.py
@@ -134,7 +134,7 @@ def parseHeader(headerfile, classname):
if (function.endswith("= 0;")):
function = function[:-4] + ";"
- print "\t", function
+ print("\t", function)
i+=1
@@ -162,7 +162,7 @@ def createDCOP(header):
def main(args):
for line in args[1:]:
- print "Going to create a dcop interface for:", line[:-1]
+ print("Going to create a dcop interface for:", line[:-1])
createDCOP(line.strip())
if __name__=="__main__":
diff --git a/chalk/doc/scripts/dcop.py b/chalk/doc/scripts/dcop.py
index cc703930f..55ac7983a 100644
--- a/chalk/doc/scripts/dcop.py
+++ b/chalk/doc/scripts/dcop.py
@@ -9,6 +9,6 @@ doc = app.KoApplicationIface.getDocuments()[0]
img=doc.currentImage()
dev=img.activeDevice()
dev.setName("A new name")
-print dev.pixelSize()
-print dev.nChannels()
-print dev.readBytes(10, 10, 1, 1)
+print(dev.pixelSize())
+print(dev.nChannels())
+print(dev.readBytes(10, 10, 1, 1))
diff --git a/chalk/plugins/viewplugins/scripting/samples/python/invert.py b/chalk/plugins/viewplugins/scripting/samples/python/invert.py
index 7a6427607..91df6d9d0 100644
--- a/chalk/plugins/viewplugins/scripting/samples/python/invert.py
+++ b/chalk/plugins/viewplugins/scripting/samples/python/invert.py
@@ -33,7 +33,7 @@ class Inverter:
script.setProgressTotalSteps(width * height)
layer.beginPainting("invert")
it = layer.createRectIterator( 0, 0, width, height )
- print "kikoo\n"
+ print("kikoo\n")
finesh = it.isDone()
while (not finesh) :
p = it.getRGBA()
@@ -42,7 +42,7 @@ class Inverter:
p[2] = 255 - p[2]
it.setRGBA(p)
script.incProgress()
- finesh = it.next()
+ finesh = next(it)
layer.endPainting()
Inverter()
diff --git a/chalk/plugins/viewplugins/scripting/samples/python/reshapehisto.py b/chalk/plugins/viewplugins/scripting/samples/python/reshapehisto.py
index 4ef66965f..a4ce7842a 100644
--- a/chalk/plugins/viewplugins/scripting/samples/python/reshapehisto.py
+++ b/chalk/plugins/viewplugins/scripting/samples/python/reshapehisto.py
@@ -42,10 +42,10 @@ def computeDiff(histo, histoTarget):
count = 1
while( count < 255 ) :
derivdiff.append((diff[count+1] - diff[count - 1])/2.0)
- print count
- print " "
- print derivdiff[count]
- print " "
+ print(count)
+ print(" ")
+ print(derivdiff[count])
+ print(" ")
count += 1
derivdiff.append(diff[255] - diff[254] )
return diff
@@ -53,7 +53,7 @@ def computeDiff(histo, histoTarget):
try:
import krosschalkcore
except:
- raise "Import of the ChalkCore module failed."
+ raise Exception("Import of the ChalkCore module failed.")
#histoTarget = [ 0.0, 0.01226531745085, 0.024528789662323, 0.0367885716726463, 0.049042819075215, 0.0612896882960706, 0.0735273368712555, 0.0857539237239997, 0.0979676094416996, 0.110166556552646, 0.122348929802458, 0.13451289643019, 0.146656626444054, 0.158778292896733, 0.170876072160234, 0.18294814420024, 0.194992692849922, 0.207007906083172, 0.218991976287209, 0.230943100534525, 0.242859480854121, 0.254739324502003, 0.266580844230888, 0.278382258559083, 0.290141792038499, 0.301857675521758, 0.313528146428344, 0.325151449009778, 0.336725834613756, 0.348249561947225, 0.359720897338346, 0.371138114997318, 0.38249949727601, 0.393803334926368, 0.405047927357568, 0.416231582891849, 0.427352619019025, 0.4384093626496, 0.449400150366478, 0.460323328675215, 0.471177254252771, 0.481960294194744, 0.492670826261026, 0.50330723911986, 0.513867932590253, 0.524351317882718, 0.534755817838293, 0.545079867165813, 0.555321912677404, 0.565480413522147, 0.575553841417885, 0.585540680881154, 0.595439429455167, 0.605248597935856, 0.614966710595909, 0.624592305406788, 0.634123934258679, 0.643560163178352, 0.652899572544893, 0.662140757303275, 0.671282327175744, 0.680322906870975, 0.689261136290974, 0.698095670735701, 0.706825181105366, 0.715448354100387, 0.723963892418968, 0.732370514952268, 0.740666956977137, 0.748851970346384, 0.756924323676554, 0.764882802533185, 0.772726209613504, 0.780453364926561, 0.788063105970749, 0.795554287908693, 0.802925783739486, 0.810176484468239, 0.817305299272921, 0.824311155668464, 0.83119299966812, 0.837949795942015, 0.84458052797292, 0.851084198209167, 0.857459828214736, 0.863706458816447, 0.869823150248263, 0.875808982292675, 0.881663054419139, 0.887384485919556, 0.892972416040772, 0.898426004114068, 0.903744429681637, 0.908926892620016, 0.913972613260457, 0.918880832506229, 0.923650811946811, 0.928281833968988, 0.93277320186481, 0.937124239936404, 0.941334293597632, 0.945402729472569, 0.949328935490789, 0.953112320979447, 0.956752316752142, 0.960248375194552, 0.963599970346811, 0.966806597982642, 0.969867775685214, 0.972783042919718, 0.97555196110265, 0.978174113667795, 0.980649106128898, 0.982976566139007, 0.985156143546496, 0.987187510447739, 0.989070361236445, 0.990804412649628, 0.99238940381023, 0.993825096266363, 0.995111274027184, 0.99624774359539, 0.997234333996328, 0.998070896803715, 0.998757306161974, 0.99929345880516, 0.999679274072503, 0.999914693920536, 0.999999682931835, 0.99993422832034, 0.999718339933283, 0.999352050249705, 0.998835414375572, 0.998168510035481, 0.997351437560967, 0.996384319875413, 0.995267302475555, 0.994000553409588, 0.992584263251893, 0.991018645074359, 0.989303934414332, 0.987440389239176, 0.985428289907469, 0.983267939126818, 0.980959661908326, 0.978503805517689, 0.975900739422957, 0.973150855238948, 0.970254566668332, 0.967212309439392, 0.964024541240472, 0.960691741651122, 0.957214412069943, 0.953593075639162, 0.949828277165924, 0.945920583040329, 0.941870581150226, 0.937678880792763, 0.933346112582728, 0.928872928357675, 0.924260001079857, 0.919508024734984, 0.914617714227821, 0.909589805274631, 0.90442505429249, 0.899124238285494, 0.89368815472786, 0.888117621443952, 0.882413476485242, 0.876576578004235, 0.870607804125365, 0.86450805281288, 0.858278241735758, 0.851919308129644, 0.845432208655849, 0.83881791925743, 0.832077435012361, 0.825211769983833, 0.818221957067693, 0.811109047837053, 0.803874112384084, 0.796518239159033, 0.789042534806467, 0.781448123998789, 0.773736149267035, 0.76590777082899, 0.757964166414642, 0.749906531088995, 0.741736077072283, 0.733454033557598, 0.725061646525966, 0.716560178558895, 0.707950908648432, 0.699235132004742, 0.690414159861254, 0.681489319277395, 0.672461952938941, 0.663333418956019, 0.654105090658787, 0.644778356390828, 0.635354619300277, 0.625835297128734, 0.616221821997965, 0.606515640194456, 0.596718211951823, 0.586831011231134, 0.576855525499155, 0.566793255504575, 0.556645715052225, 0.546414430775338, 0.536100941905873, 0.525706800042952, 0.515233568919429, 0.504682824166636, 0.49405615307734, 0.483355154366944, 0.472581437932973, 0.461736624612871, 0.450822345940161, 0.439840243898986, 0.428791970677089, 0.417679188417244, 0.406503568967204, 0.39526679362818, 0.383970552901897, 0.372616546236274, 0.361206481769749, 0.349742076074299, 0.338225053897198, 0.326657147901536, 0.315040098405551, 0.303375653120808, 0.291665566889271, 0.279911601419294, 0.268115525020586, 0.256279112338177, 0.244404144085436, 0.232492406776176, 0.220545692455878, 0.208565798432095, 0.196554527004056, 0.184513685191523, 0.172445084462932, 0.160350540462877, 0.148231872738948, 0.136090904468, 0.123929462181863, 0.111749375492553, 0.0995524768170189, 0.0873406011014653, 0.0751155855452987, 0.0628792693247314, 0.0506334933160884, 0.0383800998188613, 0.0261209322785436, 0.0138578350092972 ]
@@ -71,10 +71,10 @@ height = layer.getHeight()
countreshaping = 0
while countreshaping < 1:
histo = layer.createHistogram("RGB8HISTO",0)
- print "################################### histogram reshaping ##################################################"
+ print("################################### histogram reshaping ##################################################")
if histo == 0:
- raise "Uncompatible histogram\n"
- print "Max : " + str( histo.getMax() ) + " Min : " + str( histo.getMin() )
+ raise Exception("Uncompatible histogram")
+ print("Max : " + str( histo.getMax() ) + " Min : " + str( histo.getMin() ))
#Compute the area of the target histogram
aireHistoTarget = 0.0
@@ -133,7 +133,7 @@ while countreshaping < 1:
count += 1
it = layer.createRectIterator( 0, 0, width, height )
- print "kikoo : " + str(countreshaping)
+ print("kikoo : " + str(countreshaping))
while (not it.isDone()) :
r = it.getRed()
g = it.getGreen()
@@ -145,7 +145,7 @@ while countreshaping < 1:
it.setRed(tabler[r])
it.setGreen(tableg[g])
it.setBlue(tableb[b])
- it.next()
+ next(it)
#histo.setChannel(0)
#diff = [ ]
diff --git a/kexi/plugins/scripting/scripts/copycenter/CopyCenter.py b/kexi/plugins/scripting/scripts/copycenter/CopyCenter.py
index edcc2891b..7c934da34 100644
--- a/kexi/plugins/scripting/scripts/copycenter/CopyCenter.py
+++ b/kexi/plugins/scripting/scripts/copycenter/CopyCenter.py
@@ -27,7 +27,7 @@ class CopyCenter:
return getattr(self.plugin, plugintype)(self.plugin)
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
return None
def __init__(self, scriptpath):
@@ -38,7 +38,7 @@ class CopyCenter:
import os
import sys
if not os.path.exists(scriptpath):
- print "The Path %s does not exist" % scriptpath
+ print("The Path %s does not exist" % scriptpath)
else:
import re
regexp = re.compile('^CopyCenterPlugin(.*)\\.py$')
@@ -47,17 +47,17 @@ class CopyCenter:
if not os.path.isfile(file): continue
m = regexp.match(f)
if not m: continue
- print "Plugin name=%s file=%s" % (m.group(1),file)
+ print("Plugin name=%s file=%s" % (m.group(1),file))
mylocals = {}
try:
- execfile(file, globals(), mylocals)
- if mylocals.has_key("CopyCenterPlugin"):
+ exec(compile(open(file, "rb").read(), file, 'exec'), globals(), mylocals)
+ if "CopyCenterPlugin" in mylocals:
plugin = mylocals.get("CopyCenterPlugin")(self)
self.plugins[plugin.name] = self.Plugin(plugin)
except:
- print "Failed to import file=%s" % file
+ print("Failed to import file=%s" % file)
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
def getHomePath(self):
""" Return the homedirectory. """
@@ -163,20 +163,20 @@ def runGuiApp(copycenter, name):
#qt.TQObject.connect(self.listview, qt.SIGNAL("itemRenamed(QListViewItem*, int, const QString&)"), self.itemRenamed)
def doubleClicked(self, **args):
- print "CopyJobWidget.doubleClicked"
+ print("CopyJobWidget.doubleClicked")
item = self.listview.selectedItem()
if item and item.parent(): item.startRename(1)
def readOptions(self,domnode,plugininst):
- print "CopyJobWidget.readOptions plugintype=\"%s\"" % plugininst.plugintype
+ print("CopyJobWidget.readOptions plugintype=\"%s\"" % plugininst.plugintype)
for node in domnode.childNodes:
if node.nodeType == node.ELEMENT_NODE:
v = node.getAttribute("value")
plugininst.options[node.nodeName] = v
- print "Option \"%s\" has value \"%s\" now." % (node.nodeName, v)
+ print("Option \"%s\" has value \"%s\" now." % (node.nodeName, v))
def jobfilecomboboxChanged(self, **args):
- print "CopyJobWidget.jobfilecomboboxChanged"
+ print("CopyJobWidget.jobfilecomboboxChanged")
import os
import xml.dom.minidom
filename = str(self.jobfilecombobox.currentText())
@@ -187,16 +187,16 @@ def runGuiApp(copycenter, name):
sourcenode = elements.getElementsByTagName("Source")[0]
destinationnode = elements.getElementsByTagName("Destination")[0]
except:
- raise "The XML-file \"%s\" does not contain a valid copy-job." % filename
+ raise Exception("The XML-file \"%s\" does not contain a valid copy-job." % filename)
sourcepluginname = str(sourcenode.getAttribute('plugin'))
if not self.dialog.sourcedata.combobox.listBox().findItem(sourcepluginname,qt.TQt.ExactMatch):
- raise "There exists no plugin with the name \"%s\"." % sourcepluginname
+ raise Exception("There exists no plugin with the name \"%s\"." % sourcepluginname)
self.dialog.sourcedata.combobox.setCurrentText(sourcepluginname)
destinationpluginname = str(destinationnode.getAttribute('plugin'))
if not self.dialog.destinationdata.combobox.listBox().findItem(destinationpluginname,qt.TQt.ExactMatch):
- raise "There exists no plugin with the name \"%s\"." % destinationpluginname
+ raise Exception("There exists no plugin with the name \"%s\"." % destinationpluginname)
self.dialog.destinationdata.combobox.setCurrentText(destinationpluginname)
self.readOptions(sourcenode,self.dialog.getSourcePluginImpl())
@@ -213,10 +213,10 @@ def runGuiApp(copycenter, name):
return s.replace("&", "&amp;").replace("'", "&apos;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
def writeOptions(self,writer,pluginname,plugininst):
- print "CopyJobWidget.writeOptions"
+ print("CopyJobWidget.writeOptions")
writer.write("<%s plugin=\"%s\">\n" % (plugininst.plugintype, pluginname))
for optionname in plugininst.options:
- value = self.escape( unicode(plugininst.options[optionname]).encode("utf-8") )
+ value = self.escape( str(plugininst.options[optionname]).encode("utf-8") )
writer.write("\t<%s value=\"%s\" />\n" % (optionname,value))
writer.write("</%s>\n" % plugininst.plugintype)
@@ -236,7 +236,7 @@ def runGuiApp(copycenter, name):
self.writeOptions(f, destinationpluginname, self.dialog.getDestinationPluginImpl())
f.write("</CopyCenterJob>\n")
f.close()
- print "File \%s\" successfully written." % filename
+ print("File \%s\" successfully written." % filename)
def addItem(self, pluginimpl, afteritem = None, parentitem = None):
#print "CopyJobWidget.addItem"
@@ -262,11 +262,11 @@ def runGuiApp(copycenter, name):
def okRename(self, columnindex):
if columnindex == 1:
n = str(self.text(0))
- if not self.pluginimpl.options.has_key(n):
- raise "No such option \"%s\"" % n
+ if n not in self.pluginimpl.options:
+ raise Exception("No such option \"%s\"" % n)
qt.TQListViewItem.okRename(self,columnindex)
v = str(qt.TQListViewItem.text(self,1))
- print "Option \"%s\" has value \"%s\" now." % (n,v)
+ print("Option \"%s\" has value \"%s\" now." % (n,v))
self.pluginimpl.options[n] = v
def text(self, columnindex):
@@ -287,18 +287,18 @@ def runGuiApp(copycenter, name):
afteritem = self.addItem(pluginimpl, afteritem, item)
afteritem.setText(0,str(i))
afteritem.setText(1,str(pluginimpl.options[i]))
- print "CopyJobWidget.updateItem Added item with name \"%s\" and value \"%s\"" % (str(i),str(pluginimpl.options[i]))
+ print("CopyJobWidget.updateItem Added item with name \"%s\" and value \"%s\"" % (str(i),str(pluginimpl.options[i])))
pass
def maybeUpdate(self):
- print "CopyJobWidget.maybeUpdate"
+ print("CopyJobWidget.maybeUpdate")
self.listview.clear()
try:
self.updateItem(self.dialog.getDestinationPluginName(), self.dialog.getDestinationPluginImpl())
self.updateItem(self.dialog.getSourcePluginName(), self.dialog.getSourcePluginImpl())
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
self.listview.clear()
#--------------------------------------------------------------------
@@ -382,7 +382,7 @@ def runGuiApp(copycenter, name):
sourceimpl = self.dialog.getSourcePluginImpl()
self.textbrowser.append("Source: %s" % sourcename)
if sourceimpl == None:
- raise "No such source."
+ raise Exception("No such source.")
try:
sourceimpl.init(copierer)
@@ -391,7 +391,7 @@ def runGuiApp(copycenter, name):
destinationimpl = self.dialog.getDestinationPluginImpl()
self.textbrowser.append("<hr>Destination: %s" % destinationname)
if destinationimpl == None:
- raise "No such destination."
+ raise Exception("No such destination.")
try:
destinationimpl.init(copierer)
@@ -418,7 +418,7 @@ def runGuiApp(copycenter, name):
self.setCaption("Copy failed")
self.textbrowser.append("<b>Error: %s</b>" % sys.exc_info()[0])
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
#self.progressbar.setEnabled(False)
self.donebtn.setEnabled(True)
self.cancelbtn.setEnabled(False)
@@ -468,11 +468,11 @@ def runGuiApp(copycenter, name):
self.scrollview.viewport().setPaletteBackgroundColor(self.paletteBackgroundColor())
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
qt.TQObject.connect(self.combobox, qt.SIGNAL("activated(int)"), self.activated)
def updatePlugin(self):
- print "DataSelector.updatePlugin"
+ print("DataSelector.updatePlugin")
self.pluginimpl = None
text = str(self.combobox.currentText())
plugin = self.dialog.copycenter.plugins[text]
@@ -488,7 +488,7 @@ def runGuiApp(copycenter, name):
self.mainbox = None
def updateMainBox(self):
- print "DataSelector.updateMainBox"
+ print("DataSelector.updateMainBox")
self.removeMainBox()
self.mainbox = qt.TQVBox( self.scrollview.viewport() )
self.mainbox.setSpacing(2)
@@ -497,7 +497,7 @@ def runGuiApp(copycenter, name):
self.pluginimpl.createWidget(self.dialog, self.mainbox)
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
self.mainbox.setStretchFactor(qt.TQWidget(self.mainbox), 1)
self.mainbox.show()
self.scrollview.addChild(self.mainbox)
@@ -507,12 +507,12 @@ def runGuiApp(copycenter, name):
self.updateMainBox()
def maybeUpdate(self):
- print "DataSelector.maybeUpdate"
+ print("DataSelector.maybeUpdate")
self.removeMainBox()
qt.TQTimer.singleShot(50, self.activated)
def maybeDone(self):
- print "DataSelector.maybeDone"
+ print("DataSelector.maybeDone")
if self.pluginimpl.widget == None: return
for optionname in self.pluginimpl.options:
self.pluginimpl.options[optionname] = self.pluginimpl.widget.getOptionValue(optionname)
@@ -588,7 +588,7 @@ def runGuiApp(copycenter, name):
defaultfile = os.path.join(self.copycenter.homepath,"default.copycenterjob.xml")
if os.path.isfile(defaultfile):
- print "Reading default copy job file: %s" % defaultfile
+ print("Reading default copy job file: %s" % defaultfile)
self.jobsbox.jobfilecombobox.setCurrentText(defaultfile)
def getSourcePluginName(self):
diff --git a/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py b/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py
index 0b78bfa19..20b812123 100644
--- a/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py
+++ b/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginKexiDB.py
@@ -104,33 +104,33 @@ class CopyCenterPlugin:
self.copierer = copierer
if self.kexidbconnection == None:
if self.plugin.widget == None:
- raise "No connection established."
+ raise Exception("No connection established.")
self.copierer.appendProgressMessage("<i>Trying to connect...</i>")
if self.plugin.widget.driverbox.driver == None:
- raise "Invalid driver."
+ raise Exception("Invalid driver.")
if not self.plugin.widget.connectClicked():
- raise "Failed to connect."
+ raise Exception("Failed to connect.")
connectiondata = self.kexidbconnection.data()
self.copierer.appendProgressMessage("Connected: %s %s" % (connectiondata.driverName(),connectiondata.serverInfoString()))
tablename = str(self.plugin.widget.tablebox.tableedit.text())
if tablename == "":
- raise "No table defined"
+ raise Exception("No table defined")
fields = [ f.strip() for f in str(self.plugin.widget.fieldbox.fieldsedit.text()).split(",") if len(f) > 0 ]
if len(fields) < 1:
- raise "No fields defined"
+ raise Exception("No fields defined")
self.tableschema = self.kexidbconnection.tableSchema(tablename)
- if not self.tableschema: raise "No such tableschema \"%s\"" % tablename
+ if not self.tableschema: raise Exception("No such tableschema \"%s\"" % tablename)
self.copierer.appendProgressMessage("Table: %s" % self.tableschema.name())
if len(fields) == 1 and fields[0] == "*":
self.fieldlist = self.tableschema.fieldlist()
else:
self.fieldlist = self.tableschema.fieldlist().subList(fields)
- if not self.fieldlist: raise "No such fields \"%s\"" % fields
+ if not self.fieldlist: raise Exception("No such fields \"%s\"" % fields)
fieldlistnames = self.fieldlist.names()
- if len(fieldlistnames) < 1: raise "No valid fields defined for \"%s\"" % fields
+ if len(fieldlistnames) < 1: raise Exception("No valid fields defined for \"%s\"" % fields)
self.copierer.appendProgressMessage("Fields: %s" % fieldlistnames)
def finish(self):
if self.plugin.widget == None:
@@ -146,24 +146,24 @@ class CopyCenterPlugin:
return self.copierer == None
def initRead(self):
- print "Initialize read"
+ print("Initialize read")
#queryschema = self.plugin.copycenterplugin.drivermanager.querySchema()
queryschema = self.tableschema.query()
queryschema.fieldlist().setFields(self.fieldlist)
- print "QuerySchema: %s" % queryschema.fieldlist().names()
+ print("QuerySchema: %s" % queryschema.fieldlist().names())
whereexpression = str(self.plugin.widget.whereedit.text())
if whereexpression != "":
- print "WHERE-expression: %s" % whereexpression
+ print("WHERE-expression: %s" % whereexpression)
if not queryschema.setWhereExpression(whereexpression):
- raise "Invalid WHERE-expression."
+ raise Exception("Invalid WHERE-expression.")
#print "QuerySchema statement=%s" % queryschema.statement()
self.kexidbcursor = self.kexidbconnection.executeQuerySchema(queryschema)
if not self.kexidbcursor:
- raise "Failed to create cursor."
+ raise Exception("Failed to create cursor.")
if not self.kexidbcursor.moveFirst():
- raise "The cursor has no records to read from."
+ raise Exception("The cursor has no records to read from.")
def readRecord(self):
if self.kexidbcursor == None or self.kexidbcursor.eof():
@@ -176,15 +176,15 @@ class CopyCenterPlugin:
return record
def initWrite(self):
- print "Initialize write"
+ print("Initialize write")
def writeRecord(self,record):
- print "write record: %s" % record
+ print("write record: %s" % record)
if self.kexidbconnection.insertRecord(self.fieldlist,record):
- print "=> insert successfully"
+ print("=> insert successfully")
self.copierer.writeSuccess(record, 1)
else:
- print "=> insert failed: %s" % self.kexidbconnection.lastError()
+ print("=> insert failed: %s" % self.kexidbconnection.lastError())
self.copierer.writeFailed(record)
#import time
#time.sleep(1)
@@ -546,10 +546,10 @@ class CopyCenterPlugin:
connectiondata = self.copycenterplugin.drivermanager.createConnectionDataByFile(file)
if connectiondata == None:
- raise "Unsupported file."
+ raise Exception("Unsupported file.")
drivername = connectiondata.driverName().lower()
- print "driver: %s" % drivername
+ print("driver: %s" % drivername)
for i in range(1,self.driverbox.drivercombo.count()):
if drivername == self.driverbox.drivercombo.text(i).lower():
self.driverbox.drivercombo.setCurrentItem(i)
@@ -570,7 +570,7 @@ class CopyCenterPlugin:
def connectClicked(self):
if self.driverbox.driver == None:
- print "No driver selected."
+ print("No driver selected.")
return False
connectiondata = self.copycenterplugin.drivermanager.createConnectionData()
if self.driverbox.driver.isFileDriver():
@@ -588,18 +588,18 @@ class CopyCenterPlugin:
connectiondata.setPassword(str(self.driverbox.passedit.text()))
connectiondata.setUserName(str(self.driverbox.useredit.text()))
connectiondata.setDatabaseName(str(self.driverbox.dbedit.text()))
- print "Creating connection"
+ print("Creating connection")
connection = self.driverbox.driver.createConnection(connectiondata)
- print "Trying to connect"
+ print("Trying to connect")
if not connection.connect():
qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
return False
- print "Use database \"%s\"" % connectiondata.databaseName()
+ print("Use database \"%s\"" % connectiondata.databaseName())
if not connection.useDatabase( connectiondata.databaseName() ):
qt.TQMessageBox.critical(self,"Failed to connect",connection.lastError())
return False
- print "dbnames = %s" % connection.databaseNames()
- print "tablenames = %s" % connection.tableNames()
+ print("dbnames = %s" % connection.databaseNames())
+ print("tablenames = %s" % connection.tableNames())
#self.useDatabase(connection, filename)
self.plugin.connection.kexidbconnection = connection
diff --git a/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginQtSQL.py b/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginQtSQL.py
index 40d1a3173..76e544a6a 100644
--- a/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginQtSQL.py
+++ b/kexi/plugins/scripting/scripts/copycenter/CopyCenterPluginQtSQL.py
@@ -28,9 +28,9 @@ class CopyCenterPlugin:
def _init(self,copierer):
self.copierer = copierer
if not self.widget.connectClicked():
- raise "Failed to connect with database."
+ raise Exception("Failed to connect with database.")
if self.database == None or not self.database.isOpen():
- raise "Database is not initialized or not opened."
+ raise Exception("Database is not initialized or not opened.")
self.copierer.appendProgressMessage("Connected: %s %s@%s:%i %s" %
(str(self.database.driverName()),str(self.database.userName()),str(self.database.hostName()),self.database.port(),str(self.database.databaseName())) )
self.isfinished = False
@@ -66,25 +66,25 @@ class CopyCenterPlugin:
self.cursor = qtsql.TQSqlCursor(tablename,True,self.database)
self.cursor.setFilter(wherestatement)
if not self.cursor.select():
- raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) )
+ raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
self.fieldlist = []
for fieldname in str(self.widget.fieldedit.text()).split(","):
fn = fieldname.strip()
if fn != "":
field = self.cursor.field(fn)
if not field:
- raise "There exists no such field \"%s\" in the table \"%s\"." % (fn,tablename)
+ raise Exception("There exists no such field \"%s\" in the table \"%s\"." % (fn,tablename))
self.fieldlist.append(str(field.name()))
if len(self.fieldlist) < 1:
- raise "No fields for table \"%s\" defined." % tablename
+ raise Exception("No fields for table \"%s\" defined." % tablename)
copierer.appendProgressMessage("SQL: %s" % str(self.cursor.executedQuery()))
def read(self):
- if not self.cursor.next():
+ if not next(self.cursor):
return None
record = []
for fieldname in self.fieldlist:
- record.append( unicode(self.cursor.value(fieldname).toString()).encode("latin-1") )
+ record.append( str(self.cursor.value(fieldname).toString()).encode("latin-1") )
#print "read record: %s" % record
return record
@@ -124,14 +124,14 @@ class CopyCenterPlugin:
def initInsert(self):
self.write = self.writeInsert
if not self.cursor.select():
- raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) )
+ raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
for fieldname in self.fieldlist: # check fieldlist
field = self.cursor.field(fieldname)
- if not field: raise "There exists no such field \"%s\" in the table \"%s\"." % (fieldname, self.cursor.name())
+ if not field: raise Exception("There exists no such field \"%s\" in the table \"%s\"." % (fieldname, self.cursor.name()))
self.copierer.appendProgressMessage("Insert SQL: %s" % str(self.cursor.executedQuery()))
def writeInsert(self, record):
- print "insert record: %s" % record
+ print("insert record: %s" % record)
from TQt import qt
cursorrecord = self.cursor.primeInsert()
count = len(record)
@@ -145,9 +145,9 @@ class CopyCenterPlugin:
cursorrecord.setValue(self.fieldlist[i], v)
rowcount = self.cursor.insert()
if rowcount < 1:
- drv = unicode(self.cursor.lastError().driverText()).encode("latin-1")
- db = unicode(self.cursor.lastError().databaseText()).encode("latin-1")
- print "failed: %s %s" % (drv,db)
+ drv = str(self.cursor.lastError().driverText()).encode("latin-1")
+ db = str(self.cursor.lastError().databaseText()).encode("latin-1")
+ print("failed: %s %s" % (drv,db))
self.copierer.writeFailed(record)
else:
self.copierer.writeSuccess(record,rowcount)
@@ -158,9 +158,9 @@ class CopyCenterPlugin:
def initUpdate(self):
self.write = self.writeUpdate
self.indexfieldname = str(self.widget.indexedit.text()).strip()
- if self.indexfieldname == "": raise "No index-field defined."
+ if self.indexfieldname == "": raise Exception("No index-field defined.")
pkindex = self.cursor.index(self.indexfieldname)
- if not pkindex: raise "Invalid index-field defined."
+ if not pkindex: raise Exception("Invalid index-field defined.")
self.cursor.setPrimaryIndex(pkindex)
#self.cursor.setMode( qtsql.TQSqlCursor.Insert | qtsql.TQSqlCursor.Update )
self.copierer.appendProgressMessage("Update SQL: %s" % str(self.cursor.executedQuery()))
@@ -173,13 +173,13 @@ class CopyCenterPlugin:
indexvalue = record[idx]
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
- raise "Failed to determinate the value for the primary key."
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
+ raise Exception("Failed to determinate the value for the primary key.")
# select cursor and go to matching record.
wherestatement = "%s = \"%s\"" % (self.indexfieldname, indexvalue)
if not self.cursor.select(wherestatement):
- raise "Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) )
- if not self.cursor.next():
+ raise Exception("Select on cursor failed.<br>%s<br>%s" % ( str(self.cursor.lastError().driverText()),str(self.cursor.lastError().databaseText()) ))
+ if not next(self.cursor):
#print "No such record to update !"
return False
# Prepare updating the record.
@@ -202,7 +202,7 @@ class CopyCenterPlugin:
self.copierer.writeFailed(record)
else:
self.copierer.writeSuccess(record,rowcount)
- print "updated record (rowcount %s): %s" % (rowcount,record)
+ print("updated record (rowcount %s): %s" % (rowcount,record))
return True
def __init__(self, copycenter):
@@ -441,21 +441,21 @@ class CopyCenterPlugin:
if optionname == 'indexfield': return str(self.indexedit.text())
except:
import traceback
- print "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print("".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
return ""
def connectClicked(self):
if self.plugin.database != None and self.plugin.database.isOpen():
- print "already connected. not needed to reconnect..."
+ print("already connected. not needed to reconnect...")
self.updateConnectState()
return True
- print "trying to connect..."
+ print("trying to connect...")
from TQt import qtsql
drivername = str(self.driveredit.currentText())
- print "drivername: %s" % drivername
+ print("drivername: %s" % drivername)
connectionname = "CopyCenter%s" % self.plugin.plugintype
- print "connectionname: %s" % connectionname
+ print("connectionname: %s" % connectionname)
self.plugin.database = qtsql.TQSqlDatabase.addDatabase(drivername,connectionname)
if not self.plugin.database:
qt.TQMessageBox.critical(self,"Failed to connect","<qt>Failed to create database for driver \"%s\"</qt>" % drivername)
@@ -479,16 +479,16 @@ class CopyCenterPlugin:
if not self.plugin.database.open():
qt.TQMessageBox.critical(self,"Failed to connect","<qt>%s<br><br>%s</qt>" % (self.plugin.database.lastError().driverText(),self.plugin.database.lastError().databaseText()))
return False
- print "database is opened now!"
+ print("database is opened now!")
self.updateConnectState()
return True
def disconnectClicked(self):
- print "trying to disconnect..."
+ print("trying to disconnect...")
if self.plugin.database:
self.plugin.database.close()
self.plugin.database = None
- print "database is closed now!"
+ print("database is closed now!")
self.updateConnectState()
plugin.widget = MainWidget(plugin,self.dialog,parent)
diff --git a/kexi/plugins/scripting/scripts/exportxhtml/ExportXHTML.py b/kexi/plugins/scripting/scripts/exportxhtml/ExportXHTML.py
index cace0340c..eff0e6368 100644
--- a/kexi/plugins/scripting/scripts/exportxhtml/ExportXHTML.py
+++ b/kexi/plugins/scripting/scripts/exportxhtml/ExportXHTML.py
@@ -19,7 +19,7 @@ class Datasource:
try:
self.connection = keximainwindow.getConnection()
except:
- raise "No connection established. Please open a project before."
+ raise Exception("No connection established. Please open a project before.")
self.schema = None
@@ -65,9 +65,9 @@ class Datasource:
if not self.cursor:
self.cursor = self.connection.executeQuerySchema( self.queryschema )
if not self.cursor:
- raise "Failed to execute queryschema."
+ raise Exception("Failed to execute queryschema.")
if not self.cursor.moveFirst():
- raise "Failed to move cursor to first record."
+ raise Exception("Failed to move cursor to first record.")
if self.cursor.eof():
self.cursor = None
return None
@@ -131,7 +131,7 @@ class HtmlExporter:
if items == None: break
output.write("<tr>")
for item in items:
- u = unicode(str(self.htmlescape(item)),"latin-1")
+ u = str(str(self.htmlescape(item)),"latin-1")
output.write("<td>%s</td>" % u.encode("utf-8"))
output.write("</tr>\n")
output.write("</table>\n")
@@ -144,7 +144,7 @@ class GuiApp:
try:
import gui
except:
- raise "Import of the Kross GUI module failed."
+ raise Exception("Import of the Kross GUI module failed.")
self.dialog = gui.Dialog("Export XHTML")
self.dialog.addLabel(self.dialog, "Export a table- or query-datasource to a XHTML-file.")
@@ -176,10 +176,10 @@ class GuiApp:
def doExport(self):
file = str( self.file.get() )
query = str( self.datasourcelist.get() )
- print "Exporting '%s' to file '%s' ..." % (query,file)
+ print("Exporting '%s' to file '%s' ..." % (query,file))
if not self.datasource.setSource(query):
- raise "Invalid datasource selected."
+ raise Exceptin("Invalid datasource selected.")
#return
style = str( self.stylelist.get() )
@@ -190,7 +190,7 @@ class GuiApp:
exporter.write(f, style)
f.close()
- print "Successfully exported '%s' to file %s" % (query,file)
+ print("Successfully exported '%s' to file %s" % (query,file))
self.dialog.close()
GuiApp( Datasource() )
diff --git a/kexi/plugins/scripting/scripts/importxhtml/ImportXHTML.py b/kexi/plugins/scripting/scripts/importxhtml/ImportXHTML.py
index 200b3dee6..03a6772a8 100755
--- a/kexi/plugins/scripting/scripts/importxhtml/ImportXHTML.py
+++ b/kexi/plugins/scripting/scripts/importxhtml/ImportXHTML.py
@@ -28,7 +28,7 @@ class SaxInput:
import xml.sax.saxlib
import xml.sax.saxexts
except:
- raise "Import of the python xml.sax.saxlib module failed. This module is needed by the ImportXHTML python script."
+ raise Exception("Import of the python xml.sax.saxlib module failed. This module is needed by the ImportXHTML python script.")
def read(self, outputwriter):
""" Start reading and parsing the XML-file. """
@@ -83,7 +83,7 @@ class SaxInput:
# Print some debugging-output to stdout.
for idx in range(self.level): sys.stdout.write(' ')
sys.stdout.write('Element: %s' % name)
- for attrName in attrs.keys():
+ for attrName in list(attrs.keys()):
sys.stdout.write(' %s="%s"' % (attrName,attrs.get(attrName)))
sys.stdout.write('\n')
@@ -110,12 +110,12 @@ class SaxInput:
self.field = None
elif name == "td" and (self.level == len(self.tablebase) + 1):
#if self.field == None:
- # raise "Unexpected closing </td>"
+ # raise Exception("Unexpected closing </td>")
self.record.setField( self.field )
self.field = None
elif name == "th" and (self.level == len(self.tablebase) + 1):
#if self.field == None:
- # raise "Unexpected closing </td>"
+ # raise Exceptin("Unexpected closing </td>")
self.record.setHeader( self.field )
self.field = None
@@ -126,7 +126,7 @@ class SaxInput:
if self.field != None:
# the xml-data is unicode and we need to encode it
# to latin-1 cause KexiDB deals only with latin-1.
- u = unicode(chars[offset:offset+length])
+ u = str(chars[offset:offset+length])
self.field.append(u.encode("latin-1"))
# start the job
@@ -163,14 +163,14 @@ class KexiDBOutput:
def success(self, record):
""" Called if a record was written successfully. """
- print "SUCCESS: %s" % str(record)
+ print("SUCCESS: %s" % str(record))
self.successcount += 1
if hasattr(self.outputwriter,"logfile"):
self.addLog(record, "Success")
def failed(self, record):
""" Called if we failed to write a record. """
- print "FAILED: %s" % str(record)
+ print("FAILED: %s" % str(record))
self.failedcount += 1
if hasattr(self.outputwriter,"logfile"):
self.addLog(record, "Failed")
@@ -207,7 +207,7 @@ class KexiDBOutput:
try:
self.connection = keximainwindow.getConnection()
except:
- raise "No connection established. Please open a project before."
+ raise Exception("No connection established. Please open a project before.")
self.fieldlist = None
self.headerrecord = None
@@ -215,9 +215,9 @@ class KexiDBOutput:
def begin(self):
""" Called before parsing starts. """
- print "START JOB"
+ print("START JOB")
if self.fieldlist == None:
- raise "Invalid tableschema or fieldlist!"
+ raise Exceptin("Invalid tableschema or fieldlist!")
global KexiDBOutput
self.result = KexiDBOutput.Result(self)
if hasattr(self,"logfilename") and self.logfilename != None and self.logfilename != "":
@@ -225,7 +225,7 @@ class KexiDBOutput:
def end(self):
""" Called if parsing is fineshed. """
- print "END JOB"
+ print("END JOB")
self.logfile = None
self.mapping = {}
#self.headerrecord = None
@@ -240,12 +240,12 @@ class KexiDBOutput:
""" Set the tablename we like to import the data to. """
tableschema = self.connection.tableSchema(tablename)
if tableschema == None:
- raise "There exists no table with the name '%s'!" % tablename
+ raise Exceptin("There exists no table with the name '%s'!" % tablename)
self.fieldlist = tableschema.fieldlist()
fields = self.fieldlist.fields()
for field in fields:
- print "KexiDBOutput.setTable(%s): %s(%s)" % (tablename,field.name(),field.type())
- print "names=%s" % self.fieldlist.names()
+ print("KexiDBOutput.setTable(%s): %s(%s)" % (tablename,field.name(),field.type()))
+ print("names=%s" % self.fieldlist.names())
def setMapping(self, mapping):
""" Set the tablefieldname=xmlcolnr dictonary we should map the data to. """
@@ -277,7 +277,7 @@ class KexiDBOutput:
values = []
for k in self.fieldlist.names():
values.append( str(record.fields[ int(self.mapping[k]) ]) )
- print "Import values: %s" % values
+ print("Import values: %s" % values)
try:
if self.connection.insertRecord(self.fieldlist, values):
@@ -343,7 +343,7 @@ class GuiApp:
msgbox.show()
self.doCancel()
- except RuntimeError, e:
+ except RuntimeError as e:
pass
#except Exception, e:
# import traceback
@@ -392,7 +392,7 @@ class GuiApp:
i += 1
if not field.isAutoInc():
l.set(i)
- except ValueError, e:
+ except ValueError as e:
if not field.type() in ("Integer","BigInteger","ShortInteger","Float","Double"):
i += 1
l.set(i)
@@ -411,7 +411,7 @@ class GuiApp:
fieldname = field.name()
colnr = str( l.get() ).split(":",1)[0]
if colnr.isdigit():
- print "Table field '%s' is mapped to XML column '%s'" % (fieldname,colnr)
+ print("Table field '%s' is mapped to XML column '%s'" % (fieldname,colnr))
mapping[ fieldname ] = colnr
self.outputwriter.setMapping(mapping)
self.ok = True
diff --git a/kexi/plugins/scripting/scripts/projectdocumentor/ProjectDocumentor.py b/kexi/plugins/scripting/scripts/projectdocumentor/ProjectDocumentor.py
index 89a60301b..cb4e0de7b 100755
--- a/kexi/plugins/scripting/scripts/projectdocumentor/ProjectDocumentor.py
+++ b/kexi/plugins/scripting/scripts/projectdocumentor/ProjectDocumentor.py
@@ -20,7 +20,7 @@ class DataProvider:
try:
self.connection = keximainwindow.getConnection()
except:
- raise "No connection established. Please open the project to be documented first."
+ raise Exception("No connection established. Please open the project to be documented first.")
def printConnection(self):
condata = self.connection.data()
@@ -96,7 +96,7 @@ class GuiApp:
try:
import gui
except:
- raise "Import of the Kross GUI module failed."
+ raise Exception("Import of the Kross GUI module failed.")
self.dialog = gui.Dialog("Project Documentor")
@@ -130,7 +130,7 @@ class GuiApp:
def toHTML(self, value):
import types
result = ""
- if isinstance(value, types.TupleType):
+ if isinstance(value, tuple):
result += "<ul>"
if len(value) == 1:
result += "<li>%s</li>" % value
@@ -142,7 +142,7 @@ class GuiApp:
if i != "":
result += "<li>%s</li>" % i
result += "</ul>"
- elif isinstance(value, types.ListType):
+ elif isinstance(value, list):
for item in value:
result += "%s" % self.toHTML(item)
else:
@@ -151,7 +151,7 @@ class GuiApp:
def doSave(self):
file = str( self.file.get() )
- print "Attempting to save project documentation to file: %s" % file
+ print("Attempting to save project documentation to file: %s" % file)
f = open(file, "w")
@@ -167,19 +167,19 @@ class GuiApp:
for d in dir(self.dataprovider):
if d.startswith("print"):
- print "GuiApp.doSave() CHECK %s" % d
+ print("GuiApp.doSave() CHECK %s" % d)
a = self.printCheckBoxes[d]
if a and a.isChecked():
- print "GuiApp.doSave() BEGIN %s" % d
+ print("GuiApp.doSave() BEGIN %s" % d)
value = getattr(self.dataprovider,d)()
if value != None and len(value) > 0:
f.write("<h2>%s</h2>" % d[5:])
f.write( self.toHTML(value) )
- print "GuiApp.doSave() END %s" % d
+ print("GuiApp.doSave() END %s" % d)
f.close()
- print "Successfully saved project documentation to file: %s" % file
+ print("Successfully saved project documentation to file: %s" % file)
self.dialog.close()
GuiApp( DataProvider() )
diff --git a/kexi/plugins/scripting/scripts/python/kexiapp/__init__.py b/kexi/plugins/scripting/scripts/python/kexiapp/__init__.py
index b52243048..28cbdcada 100755
--- a/kexi/plugins/scripting/scripts/python/kexiapp/__init__.py
+++ b/kexi/plugins/scripting/scripts/python/kexiapp/__init__.py
@@ -14,7 +14,7 @@ Dual-licensed under LGPL v2+higher and the BSD license.
try:
import krosskexiapp
-except ImportError, e:
+except ImportError as e:
raise "Import of the Kross KexiApp module failed.\n%s" % e
def get(modulename):
diff --git a/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py
index d38771fc8..7d308ab2d 100755
--- a/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py
+++ b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py
@@ -18,7 +18,7 @@ import os, sys
try:
from TQt import qt
except (ImportError):
- raise "Failed to import the required PyTQt python module."
+ raise Exception("Failed to import the required PyTQt python module.")
class Dialog(tqt.QDialog):
def __init__(self, scriptpath, parent):
@@ -69,7 +69,7 @@ class Dialog(tqt.QDialog):
stylebox.setSpacing(6)
stylelabel = qt.TQLabel("Style:",stylebox)
self.stylecombo = qt.TQComboBox(stylebox)
- stylenames = self.styles.keys()
+ stylenames = list(self.styles.keys())
stylenames.sort()
for stylename in stylenames:
self.stylecombo.insertItem(stylename)
@@ -123,12 +123,13 @@ class Dialog(tqt.QDialog):
sheetname = str( self.sheetcombo.currentText() )
sheet = self.doc.sheetByName( sheetname )
- print "sheetname=%s sheet=%s" % (sheetname,sheet)
+ print("sheetname=%s sheet=%s" % (sheetname,sheet))
filename = str( self.fileedit.text() )
try:
file = open(filename, "w")
- except IOError, (errno, strerror):
+ except IOError as xxx_todo_changeme:
+ (errno, strerror) = xxx_todo_changeme.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to create HTML file \"%s\"<br><br>%s</qt>" % (filename,strerror))
return
diff --git a/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py
index e39bcc42b..a66080146 100755
--- a/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py
+++ b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py
@@ -16,7 +16,7 @@ import os, sys
try:
from TQt import qt
except (ImportError):
- raise "Failed to import the required PyTQt python module."
+ raise Exception("Failed to import the required PyTQt python module.")
####################################################################################
# Samples.
@@ -113,13 +113,13 @@ class Samples:
return (
'import krosskexidb',
'drivermanager = krosskexidb.DriverManager()',
- 'print "drivernames: %s" % drivermanager.driverNames()',
+ 'print("drivernames: %s" % drivermanager.driverNames())',
'',
'driver = drivermanager.driver( \"{DriverName}\" )',
- 'print "driver: {DriverName}"',
- 'print "version=%s.%s" % (driver.versionMajor(),driver.versionMinor())',
- 'print "mimetype=%s" % driver.fileDBDriverMimeType()',
- 'print "filedriver=%s" % driver.isFileDriver()',
+ 'print("driver: {DriverName}")',
+ 'print("version=%s.%s" % (driver.versionMajor(),driver.versionMinor())ú',
+ 'print("mimetype=%s" % driver.fileDBDriverMimeType()ú',
+ 'print("filedriver=%s" % driver.isFileDriver())',
)
class ConnectWithFile:
@@ -137,7 +137,7 @@ class Samples:
'',
'# Get the connectiondata from the project file.',
'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
- 'print "Connectiondata: %s" % connectiondata.serverInfoString()',
+ 'print("Connectiondata: %s" % connectiondata.serverInfoString())',
'',
'# Create the driver for the database backend.',
'driver = drivermanager.driver( connectiondata.driverName() )',
@@ -146,19 +146,19 @@ class Samples:
'connection = driver.createConnection(connectiondata)',
'if not connection.isConnected():',
' if not connection.connect():',
- ' raise "Failed to connect"',
+ ' raise Exception("Failed to connect")',
'',
'# Open the database for usage.',
- 'print "Databases: %s" % connection.databaseNames()',
+ 'print("Databases: %s" % connection.databaseNames())',
'if not connection.isDatabaseUsed():',
' if not connection.useDatabase( connectiondata.databaseName() ):',
' if not connection.useDatabase( connectiondata.fileName() ):',
- ' raise "Failed to use database"',
+ ' raise Exception("Failed to use database")',
'',
'# Print some infos.',
- 'print "All tables: %s" % connection.allTableNames()',
- 'print "Tables: %s" % connection.tableNames()',
- 'print "Queries: %s" % connection.queryNames()',
+ 'print("All tables: %s" % connection.allTableNames())',
+ 'print("Tables: %s" % connection.tableNames())',
+ 'print("Queries: %s" % connection.queryNames())',
)
class IterateThroughTable:
@@ -177,7 +177,7 @@ class Samples:
'',
'# Get the connectiondata from the project file.',
'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
- 'print "Connectiondata: %s" % connectiondata.serverInfoString()',
+ 'print("Connectiondata: %s" % connectiondata.serverInfoString())',
'',
'# Create the driver for the database backend.',
'driver = drivermanager.driver( connectiondata.driverName() )',
@@ -186,13 +186,13 @@ class Samples:
'connection = driver.createConnection(connectiondata)',
'if not connection.isConnected():',
' if not connection.connect():',
- ' raise "Failed to connect"',
+ ' raise Exception("Failed to connect")',
'',
'# Open the database for usage.',
'if not connection.isDatabaseUsed():',
' if not connection.useDatabase( connectiondata.databaseName() ):',
' if not connection.useDatabase( connectiondata.fileName() ):',
- ' raise "Failed to use database"',
+ ' raise Exception("Failed to use database")',
'',
'# Get the table and create a query for it.',
'table = connection.tableSchema( \"{TableName}\" )',
@@ -201,14 +201,14 @@ class Samples:
'# Create a cursor to walk through the records.',
'cursor = connection.executeQuerySchema( query )',
'if not cursor:',
- ' raise "Failed to create cursor."',
+ ' raise Exception("Failed to create cursor.")',
'',
'# Iterate through the records.',
'if not cursor.moveFirst():',
- ' raise "The cursor has no records to read from."',
+ ' raise Exception("The cursor has no records to read from.")',
'while not cursor.eof():',
' for i in range( cursor.fieldCount() ):',
- ' print "%s" % cursor.value(i)',
+ ' print("%s" % cursor.value(i))',
' cursor.moveNext()',
)
@@ -232,7 +232,7 @@ class Samples:
except:
import traceback
trace = "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
- print trace
+ print(trace)
class _CellsWidget(ListWidget):
def __init__(self, parentwidget):
@@ -279,13 +279,13 @@ class Samples:
'# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:',
- ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'',
'( (col1,row1),(col2,row2) ) = {Cells}',
'for c in range(col1,col2):',
' for r in range(row1,row2):',
' cell = sheet.cell(c,r)',
- ' print "cell c=%s r=%s v=%s" % (c,r,cell.value())',
+ ' print("cell c=%s r=%s v=%s" % (c,r,cell.value()))',
' cell.setText( \"{Value}\" )',
)
@@ -311,7 +311,7 @@ class Samples:
'# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:',
- ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'',
'( (col1,row1),(col2,row2) ) = {Cells}',
'for c in range(col1,col2):',
@@ -340,12 +340,12 @@ class Samples:
'# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:',
- ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'',
'# Iterate through the cells that have content (aka that are not empty).',
'cell = sheet.firstCell()',
'while cell:',
- ' print "col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value())',
+ ' print("col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value()))',
' cell = cell.nextCell()',
)
@@ -367,10 +367,10 @@ class Samples:
'# Get the sheet defined by the sheetname.',
'sheet = document.sheetByName( \"{SheetName}\" )',
'if not sheet:',
- ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ ' raise Exception("No such sheet {SheetName} %s" % document.sheetNames())',
'',
- 'print "name=%s" % sheet.name()',
- 'print "maxcolumns=%s maxrows=%s" % (sheet.maxColumn(),sheet.maxRow())',
+ 'print("name=%s" % sheet.name())',
+ 'print("maxcolumns=%s maxrows=%s" % (sheet.maxColumn(),sheet.maxRow()))',
)
class LoadDocFromNativeXML:
@@ -464,10 +464,10 @@ class Samples:
'document = krosskspreadcore.get("KSpreadDocument")',
'# Get the source sheet.',
'fromsheet = document.sheetByName( "{SourceSheet}" )',
- 'if not fromsheet: raise "No such sheet {SourceSheet} %s" % document.sheetNames()',
+ 'if not fromsheet: raise Exception("No such sheet {SourceSheet} %s" % document.sheetNames())',
'# Get the target sheet.',
'tosheet = document.sheetByName( "{TargetSheet}" )',
- 'if not fromsheet: raise "No such sheet {TargetSheet} %s" % document.sheetNames()',
+ 'if not fromsheet: raise Exception("No such sheet {TargetSheet} %s" % document.sheetNames())',
'# Copy the cells.',
'fromcell = fromsheet.firstCell()',
'while fromcell:',
@@ -492,13 +492,13 @@ class Samples:
'# Get the current document and the sheet.',
'document = krosskspreadcore.get("KSpreadDocument")',
'sheet = document.sheetByName( "{Sheet}" )',
- 'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()',
+ 'if not sheet: raise Exception("No such sheet {Sheet} %s" % document.sheetNames())',
'',
'filename = "{FileName}"',
'try:',
' file = open(filename, "r")',
'except IOError:',
- ' raise "Failed to open CSV File: %s" % filename',
+ ' raise Exception("Failed to open CSV File: %s" % filename)',
'',
'import csv',
'csvparser = csv.reader(file)',
@@ -530,7 +530,7 @@ class Samples:
'try:',
' file = open(filename, "w")',
'except IOError:',
- ' raise "Failed to write CSV File: %s" % filename',
+ ' raise Exception("Failed to write CSV File: %s" % filename)',
'# Prepare CSV-writer',
'import csv',
'csvwriter = csv.writer(file)',
@@ -539,7 +539,7 @@ class Samples:
'# Get the current document and the sheet.',
'document = krosskspreadcore.get("KSpreadDocument")',
'sheet = document.sheetByName( "{Sheet}" )',
- 'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()',
+ 'if not sheet: raise Exception("No such sheet {Sheet} %s" % document.sheetNames())',
'# Iterate over the cells.',
'cell = sheet.firstCell()',
'record = []',
@@ -572,7 +572,7 @@ class Samples:
return (
'from TQt import qt',
'openfilename = qt.TQFileDialog.getOpenFileName("{FileName}","*.txt *.html;;*", self)',
- 'print "openfile=%s" % openfilename',
+ 'print("openfile=%s" % openfilename)',
)
class SaveFileDialog:
@@ -587,7 +587,7 @@ class Samples:
return (
'from TQt import qt',
'savefilename = qt.TQFileDialog.getSaveFileName("{FileName}","*.txt *.html;;*", self)',
- 'print "savefile=%s" % savefilename',
+ 'print("savefile=%s" % savefilename)',
)
class CustomDialog:
@@ -631,9 +631,9 @@ class Samples:
'',
'text, ok = qt.TQInputDialog.getText("{Caption}", "{Message}", qt.TQLineEdit.Normal, "")',
'if ok:',
- ' print "Text defined: %s" % text',
+ ' print("Text defined: %s" % text)',
'else:',
- ' print "Dialog aborted."',
+ ' print("Dialog aborted.")',
)
####################################################################################
@@ -658,7 +658,7 @@ class Samples:
'd = dcopext.DCOPApp(apps[0], dcopclient)',
'result,typename,data = d.appclient.call(apps[0],"klipper","getClipboardContents()","")',
'ds = qt.TQDataStream(data, qt.IO_ReadOnly)',
- 'print "Clipboard content:\\n%s" % tdecore.dcop_next(ds, TQSTRING_OBJECT_NAME_STRING)',
+ 'print("Clipboard content:\\n%s" % tdecore.dcop_next(ds, TQSTRING_OBJECT_NAME_STRING))',
)
class AmarokCollectionInfos:
@@ -685,7 +685,7 @@ class Samples:
'',
'for funcname in ["totalAlbums","totalArtists","totalCompilations","totalGenres","totalTracks"]:',
' result,replytype,replydata = d.appclient.call("amarok", "collection", "%s()" % funcname,"")',
- ' print "%s: %s" % ( funcname, dataToList(replydata,["int"])[0] )',
+ ' print("%s: %s" % ( funcname, dataToList(replydata,["int"])[0] ))',
)
class KopeteContacts:
@@ -705,11 +705,11 @@ class Samples:
'd = dcopext.DCOPApp(app, dcopclient)',
'',
'(state,rtype,rdata) = d.appclient.call("kopete", "KopeteIface", "contacts()","")',
- 'if not state: raise "Failed to call the kopete contacts-function"',
+ 'if not state: raise Exception("Failed to call the kopete contacts-function")',
'',
'ds = qt.TQDataStream(rdata.data(), qt.IO_ReadOnly)',
'sl = tdecore.dcop_next (ds, TQSTRINGLIST_OBJECT_NAME_STRING)',
- 'print "contacts=%s" % [ str(s) for s in sl ]',
+ 'print("contacts=%s" % [ str(s) for s in sl ])',
)
class KWordSelectedText:
@@ -740,26 +740,26 @@ class Samples:
'# Get the KWord DCOP client.',
'dcopclient = tdecore.TDEApplication.dcopClient()',
'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("kword") ]',
- 'if len(apps) < 1: raise "No KWord instance is running. Please start KWord before!"',
+ 'if len(apps) < 1: raise Exception("No KWord instance is running. Please start KWord before!")',
'appname = apps[0]',
'd = dcopext.DCOPApp(appname, dcopclient)',
'',
'# Call the getDocuments() function.',
'(state,rtype,rdata) = d.appclient.call(appname, "KoApplicationIface", "getDocuments()","")',
- 'if not state: raise "%s: Failed to call getDocuments-function" % appname',
+ 'if not state: raise Exception("%s: Failed to call getDocuments-function" % appname)',
'documents = dataToList(rdata,["QValueList<DCOPRef>"])[0]',
- 'print "documents=%s" % [ str( doc.obj() ) for doc in documents ]',
+ 'print("documents=%s" % [ str( doc.obj() ) for doc in documents ])',
'document = documents[0] # Let\'s just take the first document.',
'',
'# Get the frameset.',
'ba = listToData( [ ("int",0) ] )',
'(state,rtype,rdata) = d.appclient.call(appname, document.obj(), "textFrameSet(int)", ba)',
- 'if not state: raise "%s: Failed to call frameSet-function" % appname',
+ 'if not state: raise Exception("%s: Failed to call frameSet-function" % appname)',
'frameset = dataToList( rdata,["DCOPRef"] )[0] # Let\'s just take the first textframe.',
'',
'# Get the selected text.',
'(state,rtype,rdata) = d.appclient.call(appname, frameset.obj(), "selectedText()", "")',
- 'print "Selected Text: %s" % dataToList( rdata,[TQSTRING_OBJECT_NAME_STRING] )[0]',
+ 'print("Selected Text: %s" % dataToList( rdata,[TQSTRING_OBJECT_NAME_STRING] )[0])',
)
####################################################################################
@@ -815,8 +815,8 @@ class SampleDialog(qt.TQDialog):
def getCode(self):
if not hasattr(self,"code"): return None
code = "\n".join( self.code )
- for widgetname in self.samplechild.widgets.keys():
- print ".............. %s" % widgetname
+ for widgetname in list(self.samplechild.widgets.keys()):
+ print(".............. %s" % widgetname)
widget = self.samplechild.widgets[widgetname]
value = widget.value()
if value != None:
@@ -991,9 +991,9 @@ class MainDialog(qt.TQDialog):
self.scripttext.append( code )
def execCode(self,function):
- import sys, StringIO
- codeOut = StringIO.StringIO()
- codeErr = StringIO.StringIO()
+ import sys, io
+ codeOut = io.StringIO()
+ codeErr = io.StringIO()
sys.stdout = codeOut
sys.stderr = codeErr
@@ -1009,7 +1009,7 @@ class MainDialog(qt.TQDialog):
while hasattr(tb,"tb_next") and tb.tb_next:
tb = tb.tb_next
lineno = tb.tb_lineno
- print "EXCEPTION: lineno=%s" % lineno
+ print("EXCEPTION: lineno=%s" % lineno)
self.scripttext.setCursorPosition( lineno - 1, 0 )
except:
pass
@@ -1019,12 +1019,12 @@ class MainDialog(qt.TQDialog):
s = codeErr.getvalue()
if s:
- print "ERROR:\n%s\n" % s
+ print("ERROR:\n%s\n" % s)
self.console.append(s)
s = codeOut.getvalue()
if s:
- print s
+ print(s)
self.console.append(s)
codeOut.close()
@@ -1042,7 +1042,7 @@ class MainDialog(qt.TQDialog):
self.console.clear()
def doexecute(self):
code = str( self.scripttext.text() )
- exec code in globals(), locals()
+ exec(code, globals(), locals())
self.execCode(doexecute)
self.console.append("<b>Execution done!</b>")
@@ -1058,7 +1058,8 @@ class MainDialog(qt.TQDialog):
self.scripttext.setText( str( file.read() ) )
file.close()
__main__.scripteditorfilename = filename
- except IOError, (errno, strerror):
+ except IOError as xxx_todo_changeme:
+ (errno, strerror) = xxx_todo_changeme.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (filename,strerror))
def openFileAs(self):
@@ -1073,7 +1074,8 @@ class MainDialog(qt.TQDialog):
file = open(__main__.scripteditorfilename, "w")
file.write( str( self.scripttext.text() ) )
file.close()
- except IOError, (errno, strerror):
+ except IOError as xxx_todo_changeme1:
+ (errno, strerror) = xxx_todo_changeme1.args
qt.TQMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (__main__.scripteditorfilename,strerror))
def saveFileAs(self):
diff --git a/lib/kformula/prototype/gensymbolfontmap.py b/lib/kformula/prototype/gensymbolfontmap.py
index df06eeed8..1aec3d948 100644
--- a/lib/kformula/prototype/gensymbolfontmap.py
+++ b/lib/kformula/prototype/gensymbolfontmap.py
@@ -16,14 +16,14 @@ class ContentGenerator(handler.ContentHandler):
def startElement(self, name, attrs):
if name == 'unicodetable':
self.font = None
- for (name, value) in attrs.items():
+ for (name, value) in list(attrs.items()):
if name == "font" and value:
self.font = value
if value not in fonttable:
fonttable[value] = []
elif self.font and name == 'entry':
number = ''
- for (name, value) in attrs.items():
+ for (name, value) in list(attrs.items()):
if name == "key": key = int(value)
elif name == "number": number = value
elif name == "name": latexName = value
@@ -53,13 +53,13 @@ def writeFontTable(fontname, f):
def write_header(f):
- print >>f, '''//
+ print('''//
// Created: ''' + time.ctime(time.time()) + '''
// by: gensymbolfontmap.py
// from: symbol.xml
//
// WARNING! All changes made in this file will be lost!
-'''
+''', file=f)
def main():
f = open('../symbolfontmapping.cpp', 'w')
@@ -109,8 +109,8 @@ def main():
f = open('../unicodenames.cpp', 'w')
write_header(f)
- print >>f, 'struct UnicodeNameTable { short unicode; const char* name; };'
- print >>f, 'static UnicodeNameTable nameTable[] = {'
+ print('struct UnicodeNameTable { short unicode; const char* name; };', file=f)
+ print('static UnicodeNameTable nameTable[] = {', file=f)
nameDir = {}
table = {}
for style in unicodetable:
@@ -121,9 +121,9 @@ def main():
if len(latexName) > 0:
#for fn in fontnames:
# if fontkey(fn, style, key):
- print >>f, ' { ' + key + ', "' + latexName + '" },'
+ print(' { ' + key + ', "' + latexName + '" },', file=f)
#break
- print >>f, ' { 0, 0 }\n};'
+ print(' { 0, 0 }\n};', file=f)
f.close()
@@ -132,12 +132,12 @@ def make_unicode_table():
header = []
codes = {}
f = open('../config/unicode.tbl', 'r')
- for line in f.xreadlines():
+ for line in f:
if line[0] == '#':
header.append(line.strip())
else:
break
- for line in f.xreadlines():
+ for line in f:
if len(line) > 0:
codes[line.split(',')[0].strip()] = line
f.close()
@@ -151,9 +151,9 @@ def make_unicode_table():
f = open('../config/unicode.tbl', 'w')
for line in header:
- print >> f, line
+ print(line, file=f)
for key in codes:
- print >> f, codes[key]
+ print(codes[key], file=f)
f.close()
def make_font_table(font):
@@ -178,7 +178,7 @@ def make_font_table(font):
latexName, charClass = unicodetable[key]
pos = fontkey(font, key)
if pos:
- print >> f, str(pos), key, charClass, latexName
+ print(str(pos), key, charClass, latexName, file=f)
f.close()
def make_all_font_tables():
@@ -186,30 +186,30 @@ def make_all_font_tables():
make_font_table(font)
-def symbol_entry(pos, unicode, charClass, name):
+def symbol_entry(pos, str, charClass, name):
return ' <entry key="%d" number="%s" name="%s" class="%s"/>' % \
- (pos, unicode, name, charClass)
+ (pos, str, name, charClass)
def compare_font(font):
for line in file(font+".font"):
list = line.split()
pos = int(list[0])
- unicode = list[1]
+ str = list[1]
charClass = list[2]
if len(list)>3:
name = list[3]
else:
name = ""
- if (pos, unicode) not in fonttable[font]:
- print "not in font", font, (pos, unicode)
- print symbol_entry(pos, unicode, charClass, name)
- if unicode not in unicodetable:
- print font, unicode, (name, charClass)
- print symbol_entry(pos, unicode, charClass, name)
- elif unicodetable[unicode] != (name, charClass):
- print font, unicode, pos, unicodetable[unicode], "!=", (name, charClass)
+ if (pos, str) not in fonttable[font]:
+ print("not in font", font, (pos, str))
+ print(symbol_entry(pos, str, charClass, name))
+ if str not in unicodetable:
+ print(font, str, (name, charClass))
+ print(symbol_entry(pos, str, charClass, name))
+ elif unicodetable[str] != (name, charClass):
+ print(font, str, pos, unicodetable[str], "!=", (name, charClass))
def compare():
fontnames = [ "symbol",
diff --git a/lib/kformula/prototype/unicode.py b/lib/kformula/prototype/unicode.py
index cee5ea6c1..ca495d258 100755
--- a/lib/kformula/prototype/unicode.py
+++ b/lib/kformula/prototype/unicode.py
@@ -127,21 +127,21 @@ class Widget(TQWidget):
self.fonts[self.child.fontName] = self.child.fontList()
f = open("symbol.xml", "w")
- print >> f, '<?xml version="1.0" encoding="iso-8859-1"?>'
- print >> f, '<table>'
+ print('<?xml version="1.0" encoding="iso-8859-1"?>', file=f)
+ print('<table>', file=f)
for font in self.fonts:
- print >> f, ' <unicodetable font="' + font + '">'
+ print(' <unicodetable font="' + font + '">', file=f)
for (key, number, latexName, charClass) in self.fonts[font]:
if not charClass or charClass == '':
charClass = 'ORDINARY'
- print >> f, ' <entry key="' + str(key) + \
+ print(' <entry key="' + str(key) + \
'" number="' + str(number) + \
'" name="' + str(latexName) + \
'" class="' + str(charClass) + \
- '"/>'
+ '"/>', file=f)
- print >> f, ' </unicodetable>'
- print >> f, '</table>'
+ print(' </unicodetable>', file=f)
+ print('</table>', file=f)
f.close()
@@ -153,14 +153,14 @@ class ContentGenerator(handler.ContentHandler):
def startElement(self, name, attrs):
if name == 'unicodetable':
- for (name, value) in attrs.items():
+ for (name, value) in list(attrs.items()):
if name == "font":
self.currentFont = value
self.fonts[self.currentFont] = []
elif name == 'entry':
if not self.currentFont:
raise "entry must belong to a font"
- for (name, value) in attrs.items():
+ for (name, value) in list(attrs.items()):
if name == "key":
if len(value) > 1 and value[:2] == "0x":
key = int(value[2:], 16)
diff --git a/lib/kformula/scripts/bycodes.py b/lib/kformula/scripts/bycodes.py
index 45b787a0f..fdd842693 100755
--- a/lib/kformula/scripts/bycodes.py
+++ b/lib/kformula/scripts/bycodes.py
@@ -25,11 +25,11 @@ from TQt import qt
def decode( fd, font, line ):
begin = string.find( line, '"' )
end = string.find( line, '"', begin + 1)
- unicode = line[begin + 2:end] # Remove 'U' from string aswell
+ str = line[begin + 2:end] # Remove 'U' from string aswell
char_list = []
- separation = string.find( unicode, '-' )
+ separation = string.find( str, '-' )
if separation != -1:
- second = unicode
+ second = str
while separation != -1:
first = second[0:separation]
second = second[separation + 2:]
@@ -38,13 +38,13 @@ def decode( fd, font, line ):
if separation == -1:
char_list.append( string.atoi( second, 16 ) )
else:
- char_list.append( string.atoi ( unicode, 16 ) )
+ char_list.append( string.atoi ( str, 16 ) )
fm = qt.TQFontMetrics( qt.TQFont( font ) )
in_font = True
for c in char_list:
if not fm.inFont( qt.TQChar( c ) ):
in_font = False
- fd.write( unicode + ' ' + str( in_font ) + '\n')
+ fd.write( str + ' ' + str( in_font ) + '\n')
def parse( file, font ):
fd = open( file )
diff --git a/lib/kformula/scripts/bynames.py b/lib/kformula/scripts/bynames.py
index 6b8c1d7ae..fbd1ba5e6 100755
--- a/lib/kformula/scripts/bynames.py
+++ b/lib/kformula/scripts/bynames.py
@@ -24,7 +24,7 @@ import time
import os
def write_header( f ):
- print >> f, '''//
+ print('''//
// Created: ''' + time.ctime(time.time()) + '''
// by: ''' + os.path.basename( sys.argv[0] ) + '''
// from: ''' + os.path.basename( sys.argv[1] ) + '''
@@ -49,10 +49,10 @@ def write_header( f ):
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
-'''
+''', file=f)
def write_h( f ):
- print >>f, '''
+ print('''
#ifndef ENTITIES_H
#define ENTITIES_H
@@ -74,19 +74,19 @@ extern const entityMap entities[];
KFORMULA_NAMESPACE_END
#endif // ENTITIES_H
-'''
+''', file=f)
def write_cc( fr, fw ):
- print >> fw, '''
+ print('''
#include "entities.h"
KFORMULA_NAMESPACE_BEGIN
-const entityMap entities[] = {'''
+const entityMap entities[] = {''', file=fw)
parse( fr, fw )
- print >> fw, '''
+ print('''
};
// Needed since sizeof is a macro and we cannot be used until size is known
@@ -96,7 +96,7 @@ int entityMap::size()
}
KFORMULA_NAMESPACE_END
- '''
+ ''', file=fw)
def name_cmp( a, b ):
@@ -104,7 +104,7 @@ def name_cmp( a, b ):
return -1
if a[0] > b[0]:
return 1
- print 'WARNING: Same name in entity: ' + a[0] + ', ' + b[0]
+ print('WARNING: Same name in entity: ' + a[0] + ', ' + b[0])
return 0;
def parse( fr, fw ):
@@ -133,10 +133,10 @@ def parse( fr, fw ):
while True:
e = entries.pop()
fd_list.write( e[0] + ' ' + e[1] + '\n')
- print >> fw, ' {"' + e[0] + '", ' + e[1] + '}',
+ print(' {"' + e[0] + '", ' + e[1] + '}', end=' ', file=fw)
if len( entries ) == 0:
break
- print >> fw, ','
+ print(',', file=fw)
fd_list.close()
if __name__ == '__main__':
diff --git a/lib/kformula/scripts/oper-dict.py b/lib/kformula/scripts/oper-dict.py
index e9e105508..70f7868c9 100755
--- a/lib/kformula/scripts/oper-dict.py
+++ b/lib/kformula/scripts/oper-dict.py
@@ -43,7 +43,7 @@ attr_list = [
def write_header( f ):
- print >> f, '''//
+ print('''//
// Created: ''' + time.ctime(time.time()) + '''
// by: ''' + os.path.basename( sys.argv[0] ) + '''
// from: ''' + os.path.basename( sys.argv[1] ) + '''
@@ -68,10 +68,10 @@ def write_header( f ):
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
-'''
+''', file=f)
def write_h( f ):
- print >>f, '''
+ print('''
#ifndef OPERATORDICTIONARY_H
#define OPERATORDICTIONARY_H
@@ -119,20 +119,20 @@ extern const OperatorDictionary operators[];
KFORMULA_NAMESPACE_END
#endif // OPERATORDICTIONARY_H
-'''
+''', file=f)
def write_cc( fr, fw ):
- print >> fw, '''
+ print('''
#include "operatordictionary.h"
KFORMULA_NAMESPACE_BEGIN
-const OperatorDictionary operators[] = {'''
+const OperatorDictionary operators[] = {''', file=fw)
entities = get_entities()
parse( fr, fw, entities )
- print >> fw, '''
+ print('''
};
// Needed since sizeof is a macro and we cannot be used until size is known
@@ -142,7 +142,7 @@ int OperatorDictionary::size()
}
KFORMULA_NAMESPACE_END
- '''
+ ''', file=fw)
def get_entities():
# First, read entity list into a dict
@@ -165,7 +165,7 @@ def key_cmp( a, b ):
return -1
if a[1] > b[1]:
return 1
- print 'WARNING: Same key in operator dictionary: ' + a[0] + ', ' + b[0]
+ print('WARNING: Same key in operator dictionary: ' + a[0] + ', ' + b[0])
return 0
def parse( fr, fw, entities ):
@@ -203,8 +203,8 @@ def parse( fr, fw, entities ):
# application. The best solution would probably to map to a single
# character provided by the font in the private area of Unicode
entity_name = name[begin + 1:end]
- if entities.has_key( entity_name ) :
- name = name.replace( '&' + entity_name + ';', unichr(entities[entity_name]));
+ if entity_name in entities :
+ name = name.replace( '&' + entity_name + ';', chr(entities[entity_name]));
else:
entities_found = False
break
@@ -213,9 +213,9 @@ def parse( fr, fw, entities ):
fields.pop(0) # Remove form
for f in fields:
attr, value = string.split( f, '=' )
- if not attr_dict.has_key( attr ) :
- print 'Unsupported attribute: ' + attr
- print 'If it is valid, update attribute dictionary'
+ if attr not in attr_dict :
+ print('Unsupported attribute: ' + attr)
+ print('If it is valid, update attribute dictionary')
sys.exit(-1)
# Spec has a typo, fix it
if string.count( value, '"' ) == 3:
@@ -227,20 +227,20 @@ def parse( fr, fw, entities ):
while True:
e = entries.pop()
- print >> fw, ' { {' + e[0] + ', ' + e[1] + '},'
+ print(' { {' + e[0] + ', ' + e[1] + '},', file=fw)
d = e[2]
for a in attr_list:
# Convert, at least, bool values
value = d[a]
if value == '"true"' or value == '"false"':
value = string.strip( value, '"' )
- print >> fw, '\t\t' + value,
+ print('\t\t' + value, end=' ', file=fw)
if a != attr_list[len(attr_list) - 1]:
- print >> fw, ','
- print >> fw, '}',
+ print(',', file=fw)
+ print('}', end=' ', file=fw)
if len( entries ) == 0:
break
- print >> fw, ',\n'
+ print(',\n', file=fw)
if __name__ == '__main__':
fh = open( '../operatordictionary.h', 'w' )
diff --git a/lib/kross/python/scripts/RestrictedPython/Eval.py b/lib/kross/python/scripts/RestrictedPython/Eval.py
index 841067a13..858025221 100644
--- a/lib/kross/python/scripts/RestrictedPython/Eval.py
+++ b/lib/kross/python/scripts/RestrictedPython/Eval.py
@@ -62,10 +62,10 @@ class RestrictionCapableEval:
self.expr, '<string>')
if PROFILE:
end = clock()
- print 'prepRestrictedCode: %d ms for %s' % (
- (end - start) * 1000, `self.expr`)
+ print('prepRestrictedCode: %d ms for %s' % (
+ (end - start) * 1000, repr(self.expr)))
if err:
- raise SyntaxError, err[0]
+ raise SyntaxError(err[0])
self.used = tuple(used.keys())
self.rcode = co
diff --git a/lib/kross/python/scripts/RestrictedPython/Guards.py b/lib/kross/python/scripts/RestrictedPython/Guards.py
index 4fbdcad1c..2338518fd 100644
--- a/lib/kross/python/scripts/RestrictedPython/Guards.py
+++ b/lib/kross/python/scripts/RestrictedPython/Guards.py
@@ -93,7 +93,7 @@ def _write_wrapper():
try:
f = getattr(self.ob, secattr)
except AttributeError:
- raise TypeError, error_msg
+ raise TypeError(error_msg)
f(*args)
return handler
class Wrapper:
diff --git a/lib/kross/python/scripts/RestrictedPython/Limits.py b/lib/kross/python/scripts/RestrictedPython/Limits.py
index 3b782e658..4e4511f1e 100644
--- a/lib/kross/python/scripts/RestrictedPython/Limits.py
+++ b/lib/kross/python/scripts/RestrictedPython/Limits.py
@@ -25,22 +25,22 @@ def limited_range(iFirst, *args):
elif len(args) == 2:
iStart, iEnd, iStep = iFirst, args[0], args[1]
else:
- raise AttributeError, 'range() requires 1-3 int arguments'
- if iStep == 0: raise ValueError, 'zero step for range()'
+ raise AttributeError('range() requires 1-3 int arguments')
+ if iStep == 0: raise ValueError('zero step for range()')
iLen = int((iEnd - iStart) / iStep)
if iLen < 0: iLen = 0
- if iLen >= RANGELIMIT: raise ValueError, 'range() too large'
- return range(iStart, iEnd, iStep)
+ if iLen >= RANGELIMIT: raise ValueError('range() too large')
+ return list(range(iStart, iEnd, iStep))
limited_builtins['range'] = limited_range
def limited_list(seq):
if isinstance(seq, str):
- raise TypeError, 'cannot convert string to list'
+ raise TypeError('cannot convert string to list')
return list(seq)
limited_builtins['list'] = limited_list
def limited_tuple(seq):
if isinstance(seq, str):
- raise TypeError, 'cannot convert string to tuple'
+ raise TypeError('cannot convert string to tuple')
return tuple(seq)
limited_builtins['tuple'] = limited_tuple
diff --git a/lib/kross/python/scripts/RestrictedPython/MutatingWalker.py b/lib/kross/python/scripts/RestrictedPython/MutatingWalker.py
index b0b8c9cea..7cde295dd 100644
--- a/lib/kross/python/scripts/RestrictedPython/MutatingWalker.py
+++ b/lib/kross/python/scripts/RestrictedPython/MutatingWalker.py
@@ -26,7 +26,7 @@ class MutatingWalker:
self._cache = {}
def defaultVisitNode(self, node, walker=None, exclude=None):
- for name, child in node.__dict__.items():
+ for name, child in list(node.__dict__.items()):
if exclude is not None and name in exclude:
continue
v = self.dispatchObject(child)
diff --git a/lib/kross/python/scripts/RestrictedPython/RCompile.py b/lib/kross/python/scripts/RestrictedPython/RCompile.py
index 0a538657f..dc5f8d4e4 100644
--- a/lib/kross/python/scripts/RestrictedPython/RCompile.py
+++ b/lib/kross/python/scripts/RestrictedPython/RCompile.py
@@ -52,7 +52,7 @@ class RestrictedCompileMode(AbstractCompileMode):
tree = self.parse()
MutatingWalker.walk(tree, self.rm)
if self.rm.errors:
- raise SyntaxError, self.rm.errors[0]
+ raise SyntaxError(self.rm.errors[0])
misc.set_filename(self.filename, tree)
syntax.check(tree)
return tree
@@ -66,7 +66,7 @@ class RestrictedCompileMode(AbstractCompileMode):
def compileAndTuplize(gen):
try:
gen.compile()
- except SyntaxError, v:
+ except SyntaxError as v:
return None, (str(v),), gen.rm.warnings, gen.rm.used_names
return gen.getCode(), (), gen.rm.warnings, gen.rm.used_names
diff --git a/lib/kross/python/scripts/RestrictedPython/RestrictionMutator.py b/lib/kross/python/scripts/RestrictedPython/RestrictionMutator.py
index a8b3850e0..d5f4bac02 100644
--- a/lib/kross/python/scripts/RestrictedPython/RestrictionMutator.py
+++ b/lib/kross/python/scripts/RestrictedPython/RestrictionMutator.py
@@ -26,7 +26,7 @@ from SelectCompiler import ast, parse, OP_ASSIGN, OP_DELETE, OP_APPLY
# trees without affecting line numbers shown in tracebacks, etc.
def rmLineno(node):
"""Strip lineno attributes from a code tree."""
- if node.__dict__.has_key('lineno'):
+ if 'lineno' in node.__dict__:
del node.lineno
for child in node.getChildren():
if isinstance(child, ast.Node):
diff --git a/lib/kross/python/scripts/gui.py b/lib/kross/python/scripts/gui.py
index 487a58627..693261dd5 100755
--- a/lib/kross/python/scripts/gui.py
+++ b/lib/kross/python/scripts/gui.py
@@ -34,8 +34,8 @@ class TkDialog:
""" This class is used to wrap Tkinter into a more abstract interface."""
def __init__(self, title):
- import Tkinter
- self.root = Tkinter.Tk()
+ import tkinter
+ self.root = tkinter.Tk()
self.root.title(title)
self.root.deiconify()
@@ -52,42 +52,42 @@ class TkDialog:
class Frame(Widget):
def __init__(self, dialog, parent):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
- self.widget = Tkinter.Frame(parent)
+ import tkinter
+ self.widget = tkinter.Frame(parent)
self.widget.pack()
class Label(Widget):
def __init__(self, dialog, parent, caption):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
- self.widget = Tkinter.Label(parent, text=caption)
- self.widget.pack(side=Tkinter.TOP)
+ import tkinter
+ self.widget = tkinter.Label(parent, text=caption)
+ self.widget.pack(side=tkinter.TOP)
class CheckBox(Widget):
def __init__(self, dialog, parent, caption, checked = True):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
- self.checkstate = Tkinter.IntVar()
+ import tkinter
+ self.checkstate = tkinter.IntVar()
self.checkstate.set(checked)
- self.widget = Tkinter.Checkbutton(parent, text=caption, variable=self.checkstate)
- self.widget.pack(side=Tkinter.TOP)
+ self.widget = tkinter.Checkbutton(parent, text=caption, variable=self.checkstate)
+ self.widget.pack(side=tkinter.TOP)
def isChecked(self):
return self.checkstate.get()
class List(Widget):
def __init__(self, dialog, parent, caption, items):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
+ import tkinter
- listframe = Tkinter.Frame(parent)
+ listframe = tkinter.Frame(parent)
listframe.pack()
- Tkinter.Label(listframe, text=caption).pack(side=Tkinter.LEFT)
+ tkinter.Label(listframe, text=caption).pack(side=tkinter.LEFT)
self.items = items
- self.variable = Tkinter.StringVar()
- itemlist = apply(Tkinter.OptionMenu, (listframe, self.variable) + tuple( items ))
- itemlist.pack(side=Tkinter.LEFT)
+ self.variable = tkinter.StringVar()
+ itemlist = tkinter.OptionMenu(*(listframe, self.variable) + tuple( items ))
+ itemlist.pack(side=tkinter.LEFT)
def get(self):
return self.variable.get()
def set(self, index):
@@ -96,48 +96,48 @@ class TkDialog:
class Button(Widget):
def __init__(self, dialog, parent, caption, commandmethod):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
- self.widget = Tkinter.Button(parent, text=caption, command=self.doCommand)
+ import tkinter
+ self.widget = tkinter.Button(parent, text=caption, command=self.doCommand)
self.commandmethod = commandmethod
- self.widget.pack(side=Tkinter.LEFT)
+ self.widget.pack(side=tkinter.LEFT)
def doCommand(self):
try:
self.commandmethod()
except:
#TODO why the heck we arn't able to redirect exceptions?
import traceback
- import StringIO
- fp = StringIO.StringIO()
+ import io
+ fp = io.StringIO()
traceback.print_exc(file=fp)
- import tkMessageBox
- tkMessageBox.showerror("Exception", fp.getvalue())
+ import tkinter.messagebox
+ tkinter.messagebox.showerror("Exception", fp.getvalue())
#self.dialog.root.destroy()
class Edit(Widget):
def __init__(self, dialog, parent, caption, text):
#TkDialog.Widget.__init__(self, dialog, parent)
- import Tkinter
- self.widget = Tkinter.Frame(parent)
+ import tkinter
+ self.widget = tkinter.Frame(parent)
self.widget.pack()
- label = Tkinter.Label(self.widget, text=caption)
- label.pack(side=Tkinter.LEFT)
- self.entrytext = Tkinter.StringVar()
+ label = tkinter.Label(self.widget, text=caption)
+ label.pack(side=tkinter.LEFT)
+ self.entrytext = tkinter.StringVar()
self.entrytext.set(text)
- self.entry = Tkinter.Entry(self.widget, width=36, textvariable=self.entrytext)
- self.entry.pack(side=Tkinter.LEFT)
+ self.entry = tkinter.Entry(self.widget, width=36, textvariable=self.entrytext)
+ self.entry.pack(side=tkinter.LEFT)
def get(self):
return self.entrytext.get()
class FileChooser(Edit):
def __init__(self, dialog, parent, caption, initialfile = None, filetypes = None):
TkDialog.Edit.__init__(self, dialog, parent, caption, initialfile)
- import Tkinter
+ import tkinter
self.initialfile = initialfile
self.entrytext.set(initialfile)
- btn = Tkinter.Button(self.widget, text="...", command=self.browse)
- btn.pack(side=Tkinter.LEFT)
+ btn = tkinter.Button(self.widget, text="...", command=self.browse)
+ btn.pack(side=tkinter.LEFT)
if filetypes:
self.filetypes = filetypes
@@ -150,8 +150,8 @@ class TkDialog:
d = os.path.dirname(text) or os.path.dirname(self.initialfile)
f = os.path.basename(text) or os.path.basename(self.initialfile)
- import tkFileDialog
- file = tkFileDialog.asksaveasfilename(
+ import tkinter.filedialog
+ file = tkinter.filedialog.asksaveasfilename(
initialdir=d,
initialfile=f,
#defaultextension='.html',
@@ -167,11 +167,11 @@ class TkDialog:
self.caption = str(caption)
self.message = str(message)
def show(self):
- import tkMessageBox
+ import tkinter.messagebox
if self.typename == "okcancel":
- return tkMessageBox.askokcancel(self.caption, self.message,icon=tkmessageBox.QESTION)
+ return tkinter.messagebox.askokcancel(self.caption, self.message,icon=tkmessageBox.QESTION)
else:
- tkMessageBox.showinfo(self.caption, self.message)
+ tkinter.messagebox.showinfo(self.caption, self.message)
return True
def show(self):
@@ -276,7 +276,7 @@ class TQtDialog:
def browseButtonClicked(self):
filtermask = ""
import types
- if isinstance(self.filetypes, types.TupleType):
+ if isinstance(self.filetypes, tuple):
for ft in self.filetypes:
if len(ft) == 1:
filtermask += "%s\n" % (ft[0])
@@ -289,12 +289,12 @@ class TQtDialog:
filename = None
try:
- print "TQtDialog.FileChooser.browseButtonClicked() tdefile.KFileDialog"
+ print("TQtDialog.FileChooser.browseButtonClicked() tdefile.KFileDialog")
# try to use the tdefile module included in pytde
import tdefile
filename = tdefile.KFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file")
except:
- print "TQtDialog.FileChooser.browseButtonClicked() qt.TQFileDialog"
+ print("TQtDialog.FileChooser.browseButtonClicked() qt.TQFileDialog")
# fallback to TQt filedialog
filename = qt.TQFileDialog.getOpenFileName(self.initialfile, filtermask, self, "Save to file")
if filename != None and filename != "":
@@ -341,7 +341,7 @@ class TQtDialog:
qt.TQApplication.restoreOverrideCursor()
def close(self):
- print "TQtDialog.close()"
+ print("TQtDialog.close()")
self.dialog.close()
#self.dialog.deleteLater()
@@ -352,16 +352,16 @@ class Dialog:
self.dialog = None
try:
- print "Trying to import PyTQt..."
+ print("Trying to import PyTQt...")
self.dialog = TQtDialog(title)
- print "PyTQt is our toolkit!"
+ print("PyTQt is our toolkit!")
except:
try:
- print "Failed to import PyTQt. Trying to import TkInter..."
+ print("Failed to import PyTQt. Trying to import TkInter...")
self.dialog = TkDialog(title)
- print "Falling back to TkInter as our toolkit!"
+ print("Falling back to TkInter as our toolkit!")
except:
- raise "Failed to import GUI-toolkit. Please install the PyTQt or the Tkinter python module."
+ raise Exception("Failed to import GUI-toolkit. Please install the PyTQt or the Tkinter python module.")
self.widget = self.dialog.widget
def show(self):
diff --git a/lib/kross/test/testcase.py b/lib/kross/test/testcase.py
index 28917f874..6db6d980a 100644
--- a/lib/kross/test/testcase.py
+++ b/lib/kross/test/testcase.py
@@ -59,84 +59,84 @@ class TestPlugin(unittest.TestCase):
def setUp(self):
import krosstestpluginmodule
self.pluginobject1 = krosstestpluginmodule.testpluginobject1()
- self.assert_( self.pluginobject1 )
+ self.assertTrue( self.pluginobject1 )
self.pluginobject2 = krosstestpluginmodule.testpluginobject2()
- self.assert_( self.pluginobject2 )
+ self.assertTrue( self.pluginobject2 )
self.testqobject1 = krosstestpluginmodule.testqobject1()
- self.assert_( self.testqobject1 )
+ self.assertTrue( self.testqobject1 )
def testBasicDataTypes(self):
- self.assert_( self.pluginobject1.uintfunc(177321) == 177321 )
- self.assert_( self.pluginobject1.intfunc(93675) == 93675 )
- self.assert_( self.pluginobject1.intfunc(-73673) == -73673 )
- self.assert_( self.pluginobject1.boolfunc(True) == True )
- self.assert_( self.pluginobject1.boolfunc(False) == False )
- self.assert_( self.pluginobject1.doublefunc(4265.3723) == 4265.3723 )
- self.assert_( self.pluginobject1.doublefunc(-4265.68) == -4265.68 )
- self.assert_( self.pluginobject1.cstringfunc(" This is a Test! ") == " This is a Test! " )
- self.assert_( self.pluginobject1.stringfunc(" Another \n\r Test! $%&\"") == " Another \n\r Test! $%&\"" )
+ self.assertTrue( self.pluginobject1.uintfunc(177321) == 177321 )
+ self.assertTrue( self.pluginobject1.intfunc(93675) == 93675 )
+ self.assertTrue( self.pluginobject1.intfunc(-73673) == -73673 )
+ self.assertTrue( self.pluginobject1.boolfunc(True) == True )
+ self.assertTrue( self.pluginobject1.boolfunc(False) == False )
+ self.assertTrue( self.pluginobject1.doublefunc(4265.3723) == 4265.3723 )
+ self.assertTrue( self.pluginobject1.doublefunc(-4265.68) == -4265.68 )
+ self.assertTrue( self.pluginobject1.cstringfunc(" This is a Test! ") == " This is a Test! " )
+ self.assertTrue( self.pluginobject1.stringfunc(" Another \n\r Test! $%&\"") == " Another \n\r Test! $%&\"" )
#TODO
#self.assert_( self.pluginobject1.stringfunc( unicode(" Unicode test ") ) == " Unicode test " )
#self.assert_( self.pluginobject1.stringfunc(unicode(" Another Test! ")) == unicode(" Another Test! ") )
- self.assert_( self.pluginobject1.stringstringfunc("MyString1", "MyString2") == "MyString1" )
- self.assert_( self.pluginobject1.uintdoublestringfunc(8529,285.246,"String") == 8529 )
- self.assert_( self.pluginobject1.stringlistbooluintdouble(["s1","s2"],True,6,7.0,"String") == ["s1","s2"] )
+ self.assertTrue( self.pluginobject1.stringstringfunc("MyString1", "MyString2") == "MyString1" )
+ self.assertTrue( self.pluginobject1.uintdoublestringfunc(8529,285.246,"String") == 8529 )
+ self.assertTrue( self.pluginobject1.stringlistbooluintdouble(["s1","s2"],True,6,7.0,"String") == ["s1","s2"] )
def testStringList(self):
- self.assert_( self.pluginobject1.stringlistfunc( [] ) == [] )
- self.assert_( self.pluginobject1.stringlistfunc( ["First Item"," Second Item "] ) == ["First Item"," Second Item "] )
- self.assert_( self.pluginobject1.stringlistfunc( ("Theird Item"," Forth Item ","Fifth Item") ) == ["Theird Item"," Forth Item ","Fifth Item"] )
+ self.assertTrue( self.pluginobject1.stringlistfunc( [] ) == [] )
+ self.assertTrue( self.pluginobject1.stringlistfunc( ["First Item"," Second Item "] ) == ["First Item"," Second Item "] )
+ self.assertTrue( self.pluginobject1.stringlistfunc( ("Theird Item"," Forth Item ","Fifth Item") ) == ["Theird Item"," Forth Item ","Fifth Item"] )
def testVariant(self):
- self.assert_( self.pluginobject1.variantfunc(True) == True )
- self.assert_( self.pluginobject1.variantfunc(False) == False )
- self.assert_( self.pluginobject1.variantfunc(187937) == 187937 )
- self.assert_( self.pluginobject1.variantfunc(-69825) == -69825 )
- self.assert_( self.pluginobject1.variantfunc(8632.274) == 8632.274 )
- self.assert_( self.pluginobject1.variantfunc(-8632.351) == -8632.351 )
- self.assert_( self.pluginobject1.variantfunc(" Test \n\r This String $%&\"") == " Test \n\r This String $%&\"")
+ self.assertTrue( self.pluginobject1.variantfunc(True) == True )
+ self.assertTrue( self.pluginobject1.variantfunc(False) == False )
+ self.assertTrue( self.pluginobject1.variantfunc(187937) == 187937 )
+ self.assertTrue( self.pluginobject1.variantfunc(-69825) == -69825 )
+ self.assertTrue( self.pluginobject1.variantfunc(8632.274) == 8632.274 )
+ self.assertTrue( self.pluginobject1.variantfunc(-8632.351) == -8632.351 )
+ self.assertTrue( self.pluginobject1.variantfunc(" Test \n\r This String $%&\"") == " Test \n\r This String $%&\"")
def testObjects(self):
- print "-----------------1"
+ print("-----------------1")
newobjref = self.pluginobject1.objectfunc(self.pluginobject2)
- print "-----------------2"
- print str(newobjref)
+ print("-----------------2")
+ print(str(newobjref))
#self.assert_( newobjref.myuniqueid == self.pluginobject2.myuniqueid )
#print "===========> %s" % self.pluginobject2.myName()
- print "testqobject1 properties=%s" % self.testqobject1.propertyNames()
- print "testqobject1 Q_SLOTS=%s" % self.testqobject1.slotNames()
- print "testqobject1 Q_SIGNALS=%s" % self.testqobject1.signalNames()
- print "-----------------3"
- print "DIR=>%s" % dir(self.testqobject1)
+ print("testqobject1 properties=%s" % self.testqobject1.propertyNames())
+ print("testqobject1 Q_SLOTS=%s" % self.testqobject1.slotNames())
+ print("testqobject1 Q_SIGNALS=%s" % self.testqobject1.signalNames())
+ print("-----------------3")
+ print("DIR=>%s" % dir(self.testqobject1))
- print "===================> slotcall-result: %s" % self.testqobject1.slot("self()")
+ print("===================> slotcall-result: %s" % self.testqobject1.slot("self()"))
#testobject = newobjref.get("TestObject")
#print testobject
- print "-----------------9"
+ print("-----------------9")
def testDefaultArguments(self):
- self.assert_( self.pluginobject1.uintfunc_defarg(98765) == 98765 )
- self.assert_( self.pluginobject1.uintfunc_defarg() == 12345 )
- self.assert_( self.pluginobject1.stringfunc_defarg("MyString") == "MyString" )
- self.assert_( self.pluginobject1.stringfunc_defarg() == "MyDefaultString" )
- self.assert_( self.pluginobject1.stringlistfunc_defarg(["s1","s2","s3"]) == ["s1","s2","s3"] )
- self.assert_( self.pluginobject1.stringlistfunc_defarg() == ["Default1","Default2"] )
- self.assert_( self.pluginobject1.variantfunc_defarg(822.75173) == 822.75173 )
- self.assert_( self.pluginobject1.variantfunc_defarg() == "MyDefaultVariantString" )
+ self.assertTrue( self.pluginobject1.uintfunc_defarg(98765) == 98765 )
+ self.assertTrue( self.pluginobject1.uintfunc_defarg() == 12345 )
+ self.assertTrue( self.pluginobject1.stringfunc_defarg("MyString") == "MyString" )
+ self.assertTrue( self.pluginobject1.stringfunc_defarg() == "MyDefaultString" )
+ self.assertTrue( self.pluginobject1.stringlistfunc_defarg(["s1","s2","s3"]) == ["s1","s2","s3"] )
+ self.assertTrue( self.pluginobject1.stringlistfunc_defarg() == ["Default1","Default2"] )
+ self.assertTrue( self.pluginobject1.variantfunc_defarg(822.75173) == 822.75173 )
+ self.assertTrue( self.pluginobject1.variantfunc_defarg() == "MyDefaultVariantString" )
#def testExpectedFailures(self):
# to less arguments
#self.assertRaises(ValueError, self.pluginobject1.uintfunc)
#self.assert_( self.pluginobject1.uintfunc() != 8465 )
-print "__name__ = %s" % __name__
+print("__name__ = %s" % __name__)
#print "self = %s" % self
#print self.get("TestObject")
diff --git a/lib/kross/test/testgui.py b/lib/kross/test/testgui.py
index b5efb8dc4..0a3cf822d 100644
--- a/lib/kross/test/testgui.py
+++ b/lib/kross/test/testgui.py
@@ -8,32 +8,32 @@
class TkTest:
def __init__(self):
- import Tkinter
- self.root = Tkinter.Tk()
+ import tkinter
+ self.root = tkinter.Tk()
self.root.title("TkTest")
self.root.deiconify()
- self.mainframe = Tkinter.Frame(self.root)
+ self.mainframe = tkinter.Frame(self.root)
self.mainframe.pack()
- self.button1 = Tkinter.Button(self.mainframe, text="Button1", command=self.callback1)
- self.button1.pack(side=Tkinter.LEFT)
+ self.button1 = tkinter.Button(self.mainframe, text="Button1", command=self.callback1)
+ self.button1.pack(side=tkinter.LEFT)
- self.button2 = Tkinter.Button(self.mainframe, text="Button2", command=self.callback2)
- self.button2.pack(side=Tkinter.LEFT)
+ self.button2 = tkinter.Button(self.mainframe, text="Button2", command=self.callback2)
+ self.button2.pack(side=tkinter.LEFT)
- self.exitbutton = Tkinter.Button(self.mainframe, text="Exit", command=self.root.destroy)
- self.exitbutton.pack(side=Tkinter.LEFT)
+ self.exitbutton = tkinter.Button(self.mainframe, text="Exit", command=self.root.destroy)
+ self.exitbutton.pack(side=tkinter.LEFT)
self.root.mainloop()
def callback1(self):
- import tkMessageBox
- tkMessageBox.showinfo("Callback1", "Callback1 called.")
+ import tkinter.messagebox
+ tkinter.messagebox.showinfo("Callback1", "Callback1 called.")
def callback2(self):
- import tkMessageBox
- tkMessageBox.showinfo("Callback2", "Callback2 called.")
+ import tkinter.messagebox
+ tkinter.messagebox.showinfo("Callback2", "Callback2 called.")
class TQtTest:
def __init__(self):
@@ -41,7 +41,7 @@ class TQtTest:
class Button(qt.TQPushButton):
def __init__(self, *args):
- apply(qt.TQPushButton.__init__, (self,) + args)
+ qt.TQPushButton.__init__(*(self,) + args)
class ComboBox(qt.TQHBox):
def __init__(self, parent, caption, items = []):
@@ -56,7 +56,7 @@ class TQtTest:
class FileChooser(qt.TQHBox):
def __init__(self, *args):
- apply(qt.TQHBox.__init__, (self,) + args)
+ qt.TQHBox.__init__(*(self,) + args)
self.defaultfilename = "~/output.html"
self.setSpacing(6)
@@ -119,7 +119,7 @@ class TQtTest:
qt.TQObject.connect(cancelbutton, qt.SIGNAL("clicked()"), self, qt.SLOT("close()"))
def accept(self):
- print "ACCEPTTTTTTTT !!!!!!!!!!!!!!!!!!!!!!!!!!!!"
+ print("ACCEPTTTTTTTT !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
file = qt.TQFile( self.filechooser.file() )
#if not file.exists():
@@ -128,13 +128,13 @@ class TQtTest:
# print "File '%s' does exist." % self.filechooser.file()
def exportButtonClicked(self):
- print "Export to HTML !!!!!!!!!!!!!!!!!!!!!!!!!!!!"
+ print("Export to HTML !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
def __getattr__(self, attr):
- print "=> Dialog.__getattr__(self,attr)"
+ print("=> Dialog.__getattr__(self,attr)")
#def closeEvent(self, ev): pass
def event(self, e):
- print "=> Dialog.event %s" % e
+ print("=> Dialog.event %s" % e)
#self.deleteLater()
#support.swapThreadState() # calls appropriate c-function
return qt.TQDialog.event(self, e)
@@ -143,7 +143,7 @@ class TQtTest:
dialog = Dialog(app.mainWidget(), "Dialog", 1)
dialog.show()
-print "################## BEGIN"
+print("################## BEGIN")
#TkTest()
TQtTest()
-print "################## END"
+print("################## END")
diff --git a/lib/kross/test/testkexidb.py b/lib/kross/test/testkexidb.py
index 803d65486..c85f98067 100644
--- a/lib/kross/test/testkexidb.py
+++ b/lib/kross/test/testkexidb.py
@@ -15,36 +15,36 @@ class KexiDBClass:
#import KexiDB
import krosskexidb
self.kexidbmodule = krosskexidb
- print "KrossKexiDB version=%s" % self.kexidbmodule.version()
+ print("KrossKexiDB version=%s" % self.kexidbmodule.version())
# Create and remember the drivermanager.
self.drivermanager = self.kexidbmodule.DriverManager()
# Print informations about the KexiDB module.
def printKexiDB(self):
- print "KexiDB = %s %s" % (str(self.kexidbmodule),dir(self.kexidbmodule))
+ print("KexiDB = %s %s" % (str(self.kexidbmodule),dir(self.kexidbmodule)))
# Each object has __name__ and __doc__
#print "KexiDB.__name__ = %s" % self.kexidbmodule.__name__
#print "KexiDB.__doc__ = %s" % self.kexidbmodule.__doc__
# Print some infos about the drivermanager.
- print "drivermanager = %s %s" % (self.drivermanager,dir(self.drivermanager))
+ print("drivermanager = %s %s" % (self.drivermanager,dir(self.drivermanager)))
# The drivermanager holds a list of drivers he supports.
- print "drivermanager.driverNames() = %s" % self.driverNames()
+ print("drivermanager.driverNames() = %s" % self.driverNames())
# Print informations about a driver.
def printDriverManger(self, driver):
- print "driver = %s %s" % (driver,dir(driver))
+ print("driver = %s %s" % (driver,dir(driver)))
# Each driver has a version to be able to determinate with what release we are working.
- print "driver.versionMajor() = %s" % driver.versionMajor()
- print "driver.versionMinor() = %s" % driver.versionMinor()
+ print("driver.versionMajor() = %s" % driver.versionMajor())
+ print("driver.versionMinor() = %s" % driver.versionMinor())
# Show us what connections are opened right now.
- print "driver.connectionsList() = %s" % str(driver.connectionsList())
+ print("driver.connectionsList() = %s" % str(driver.connectionsList()))
# Print informations about a connection.
def printConnection(self, connection):
- print "connection = %s %s" % (str(connection),dir(connection))
+ print("connection = %s %s" % (str(connection),dir(connection)))
# Print a list of all avaible databasenames this connection has.
- print "connection.databaseNames() = %s" % connection.databaseNames()
+ print("connection.databaseNames() = %s" % connection.databaseNames())
# Return a list of drivernames.
def driverNames(self):
@@ -65,7 +65,7 @@ class KexiDBClass:
# Fill the new connectiondata object with what we need to connect.
connectiondata.setCaption("myFileConnection")
connectiondata.setFileName(filename)
- print "connectiondata.serverInfoString = %s" % connectiondata.serverInfoString()
+ print("connectiondata.serverInfoString = %s" % connectiondata.serverInfoString())
# Create the connection now.
connection = driver.createConnection(connectiondata)
# Establish the connection.
@@ -98,23 +98,23 @@ class KexiDBClass:
def testParser(self, connection, sqlstatement):
parser = connection.parser()
if not parser:
- raise "ERROR in testParser(): Failed to create parser!"
- print "parser.parse = %s" % parser.parse(sqlstatement)
- print "parser.statement = %s" % parser.statement()
- print "parser.operation = %s" % parser.operation()
- print "parser.table = %s" % parser.table()
- print "parser.query = %s" % parser.query()
- print "parser.connection = %s" % parser.connection()
+ raise("ERROR in testParser(): Failed to create parser!")
+ print("parser.parse = %s" % parser.parse(sqlstatement))
+ print("parser.statement = %s" % parser.statement())
+ print("parser.operation = %s" % parser.operation())
+ print("parser.table = %s" % parser.table())
+ print("parser.query = %s" % parser.query())
+ print("parser.connection = %s" % parser.connection())
# Execute the sql query statement and print the single string result.
def printQuerySingleString(self, connection, sqlstatement):
query = myfileconnection.querySingleString("SELECT * FROM table1", 0)
- print "querySingleString = %s" % query
+ print("querySingleString = %s" % query)
# Execute the sql query statement and print the single stringlist result.
def printQueryStringList(self, connection, sqlstatement):
query = myfileconnection.queryStringList("SELECT * FROM table1", 0)
- print "queryStringList = %s" % query
+ print("queryStringList = %s" % query)
# Walk through the KexiDBCursor and print all item values.
def printQueryCursor(self, cursor):
@@ -130,7 +130,7 @@ class KexiDBClass:
while(not cursor.eof()):
# Print for each item some infos about the fields and there content.
for i in range( cursor.fieldCount() ):
- print "Item='%s' Field='%s' Value='%s'" % (cursor.at(), i, cursor.value(i))
+ print("Item='%s' Field='%s' Value='%s'" % (cursor.at(), i, cursor.value(i)))
# Move to the next item
cursor.moveNext()
@@ -148,7 +148,7 @@ class KexiDBClass:
field.setType("Text")
field.setName(name)
tableschema.fieldlist().addField(field)
- print "tableschema.fieldlist().fieldCount() = %s" % tableschema.fieldlist().fieldCount()
+ print("tableschema.fieldlist().fieldCount() = %s" % tableschema.fieldlist().fieldCount())
return field
# Create a table.
@@ -156,7 +156,7 @@ class KexiDBClass:
# First we need a new tableschema.
tableschema = self.drivermanager.tableSchema(tablename)
self.addField(tableschema, "myfield")
- print "connection.createTable = %s" % connection.createTable(tableschema, True)
+ print("connection.createTable = %s" % connection.createTable(tableschema, True))
return tableschema
# Drop a table.
@@ -166,7 +166,7 @@ class KexiDBClass:
# Alter the name of a table.
def alterTableName(self, connection, tablename, newtablename):
tableschema = connection.tableSchema(tablename)
- print "alterTableName from=%s to=%s tableschema=%s" % (tablename, newtablename, tableschema)
+ print("alterTableName from=%s to=%s tableschema=%s" % (tablename, newtablename, tableschema))
connection.alterTableName(tableschema, newtablename)
def testKexiDB():
@@ -209,6 +209,6 @@ def testKexiDB():
#del(mydriver)
#del(mykexidbclass)
-print "########## BEGIN TEST: KexiDB ##########"
+print("########## BEGIN TEST: KexiDB ##########")
testKexiDB()
-print "########## END TEST: KexiDB ##########"
+print("########## END TEST: KexiDB ##########")
diff --git a/lib/kross/test/testperformance.py b/lib/kross/test/testperformance.py
index a76453ed8..bd9c6d2c8 100755
--- a/lib/kross/test/testperformance.py
+++ b/lib/kross/test/testperformance.py
@@ -10,7 +10,7 @@ def runner():
testobject1 = krosstestpluginmodule.testpluginobject1()
def testKexiDB(kexidbfile,drivername,sqlstring):
- print "test kexidb"
+ print("test kexidb")
import krosskexidb
drivermanager = krosskexidb.DriverManager()
connectiondata = drivermanager.createConnectionData()
@@ -29,7 +29,7 @@ def runner():
cursor.moveNext()
def test1():
- print "test1"
+ print("test1")
for i in range(100000):
testobject1.func1()
testobject1.func1()