Updated 'print' statements throughout Appy code, in order to be Python3x as well as Python2x-compliant.

This commit is contained in:
Gaetan Delannay 2013-05-30 00:46:11 +02:00
parent e8c63f225f
commit 0c50fe188a
24 changed files with 92 additions and 92 deletions

View file

@ -41,7 +41,7 @@ class AskSap:
def manageArgs(self, parser, options, args): def manageArgs(self, parser, options, args):
# Check number of args # Check number of args
if len(args) != 5: if len(args) != 5:
print WRONG_NG_OF_ARGS print(WRONG_NG_OF_ARGS)
parser.print_help() parser.print_help()
sys.exit(ERROR_CODE) sys.exit(ERROR_CODE)
@ -59,10 +59,10 @@ class AskSap:
if not password: if not password:
password = getpass.getpass('Password for the SAP user: ') password = getpass.getpass('Password for the SAP user: ')
connectionParams = args[:4] + [password] connectionParams = args[:4] + [password]
print 'Connecting to SAP...' print('Connecting to SAP...')
sap = Sap(*connectionParams) sap = Sap(*connectionParams)
sap.connect() sap.connect()
print 'Connected.' print('Connected.')
sapElement = args[4] sapElement = args[4]
if options.isGroup: if options.isGroup:
# Returns info about the functions available in this group of # Returns info about the functions available in this group of
@ -73,8 +73,8 @@ class AskSap:
# Return info about a given function. # Return info about a given function.
info = sap.getFunctionInfo(sapElement) info = sap.getFunctionInfo(sapElement)
prefix = 'Function' prefix = 'Function'
print '%s: %s' % (prefix, sapElement) print('%s: %s' % (prefix, sapElement))
print info print(info)
sap.disconnect() sap.disconnect()
except SapError, se: except SapError, se:
sys.stderr.write(str(se)) sys.stderr.write(str(se))

View file

@ -217,7 +217,7 @@ class ZodbBackuper:
if self.emails: if self.emails:
self.sendEmails() self.sendEmails()
self.logFile.close() self.logFile.close()
print self.logMem.getvalue() print(self.logMem.getvalue())
self.logMem.close() self.logMem.close()
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------

View file

@ -16,7 +16,7 @@ class LdapTester:
def __init__(self): def __init__(self):
# Get params from shell args. # Get params from shell args.
if len(sys.argv) != 7: if len(sys.argv) != 7:
print LdapTester.__doc__ print(LdapTester.__doc__)
sys.exit(0) sys.exit(0)
s = self s = self
s.uri, s.login, s.password, s.base, s.attrs, s.filter = sys.argv[1:] s.uri, s.login, s.password, s.base, s.attrs, s.filter = sys.argv[1:]
@ -28,25 +28,25 @@ class LdapTester:
def test(self): def test(self):
# Connect the the LDAP # Connect the the LDAP
print 'Creating server object for server %s...' % self.uri print('Creating server object for server %s...' % self.uri)
server = ldap.initialize(self.uri) server = ldap.initialize(self.uri)
print 'Done. Login with %s...' % self.login print('Done. Login with %s...' % self.login)
server.simple_bind(self.login, self.password) server.simple_bind(self.login, self.password)
if self.ssl: if self.ssl:
server.start_tls_s() server.start_tls_s()
try: try:
for i in range(self.tentatives): for i in range(self.tentatives):
try: try:
print 'Done. Performing a simple query on %s...' % self.base print('Done. Performing a simple query on %s...'% self.base)
res = server.search_st( res = server.search_st(
self.base, ldap.SCOPE_ONELEVEL, filterstr=self.filter, self.base, ldap.SCOPE_ONELEVEL, filterstr=self.filter,
attrlist=self.attrs, timeout=5) attrlist=self.attrs, timeout=5)
print 'Got %d entries' % len(res) print('Got %d entries' % len(res))
break break
except ldap.TIMEOUT: except ldap.TIMEOUT:
print 'Got timeout.' print('Got timeout.')
except ldap.LDAPError, le: except ldap.LDAPError, le:
print le.__class__.__name__, le print('%s %s' % (le.__class__.__name__, str(le)))
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -20,21 +20,21 @@ class LoChecker:
# Call LO in server mode to convert self.odtFile to PDF # Call LO in server mode to convert self.odtFile to PDF
converter = os.path.join(self.appyFolder, 'pod', 'converter.py') converter = os.path.join(self.appyFolder, 'pod', 'converter.py')
cmd = 'python %s %s pdf -p %d' % (converter, self.odtFile, self.port) cmd = 'python %s %s pdf -p %d' % (converter, self.odtFile, self.port)
print cmd print(cmd)
os.system(cmd) os.system(cmd)
# Check if the PDF was generated # Check if the PDF was generated
pdfFile = '%s.pdf' % os.path.splitext(self.odtFile)[0] pdfFile = '%s.pdf' % os.path.splitext(self.odtFile)[0]
if not os.path.exists(pdfFile): if not os.path.exists(pdfFile):
print 'PDF was not generated.' print('PDF was not generated.')
else: else:
os.remove(pdfFile) os.remove(pdfFile)
print 'Check successfull.' print('Check successfull.')
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
nbOfArgs = len(sys.argv) nbOfArgs = len(sys.argv)
if nbOfArgs not in (1, 2): if nbOfArgs not in (1, 2):
print usage print(usage)
sys.exit() sys.exit()
# Get the nb of args # Get the nb of args
port = (nbOfArgs == 2) and int(sys.argv[1]) or 2002 port = (nbOfArgs == 2) and int(sys.argv[1]) or 2002

View file

@ -32,5 +32,4 @@ if not os.path.exists(scriptName):
f.close() f.close()
os.system('chmod -R 755 %s' % repoFolder) os.system('chmod -R 755 %s' % repoFolder)
os.chdir(curdir) os.chdir(curdir)
print 'Repository created.' print('Repository created.')

View file

@ -110,12 +110,12 @@ class EggifyScript:
eggFullName = j(self.eggFolder, self.eggName) eggFullName = j(self.eggFolder, self.eggName)
if os.path.exists(eggFullName): if os.path.exists(eggFullName):
os.remove(eggFullName) os.remove(eggFullName)
print 'Existing "%s" was removed.' % eggFullName print('Existing "%s" was removed.' % eggFullName)
# Create a temp folder where to store the egg # Create a temp folder where to store the egg
eggTempFolder = os.path.splitext(eggFullName)[0] eggTempFolder = os.path.splitext(eggFullName)[0]
if os.path.exists(eggTempFolder): if os.path.exists(eggTempFolder):
FolderDeleter.delete(eggTempFolder) FolderDeleter.delete(eggTempFolder)
print 'Removed "%s" that was in my way.' % eggTempFolder print('Removed "%s" that was in my way.' % eggTempFolder)
os.mkdir(eggTempFolder) os.mkdir(eggTempFolder)
# Create the "Products" sub-folder if we must wrap the package in this # Create the "Products" sub-folder if we must wrap the package in this
# namespace # namespace

View file

@ -53,12 +53,12 @@ class GeneratorScript:
def manageArgs(self, parser, options, args): def manageArgs(self, parser, options, args):
# Check number of args # Check number of args
if len(args) != 1: if len(args) != 1:
print WRONG_NG_OF_ARGS print(WRONG_NG_OF_ARGS)
parser.print_help() parser.print_help()
sys.exit(ERROR_CODE) sys.exit(ERROR_CODE)
# Check existence of application # Check existence of application
if not os.path.exists(args[0]): if not os.path.exists(args[0]):
print APP_NOT_FOUND % args[0] print(APP_NOT_FOUND % args[0])
sys.exit(ERROR_CODE) sys.exit(ERROR_CODE)
# Convert app path to an absolute path # Convert app path to an absolute path
args[0] = os.path.abspath(args[0]) args[0] = os.path.abspath(args[0])
@ -76,8 +76,8 @@ class GeneratorScript:
(options, args) = optParser.parse_args() (options, args) = optParser.parse_args()
try: try:
self.manageArgs(optParser, options, args) self.manageArgs(optParser, options, args)
print 'Appy version:', appy.version.verbose print('Appy version: %s' % appy.version.verbose)
print 'Generating Zope product in %s/zope...' % args[0] print('Generating Zope product in %s/zope...' % args[0])
ZopeGenerator(args[0], options).run() ZopeGenerator(args[0], options).run()
# Give the user some statistics about its code # Give the user some statistics about its code
LinesCounter(args[0], excludes=['%szope' % os.sep]).run() LinesCounter(args[0], excludes=['%szope' % os.sep]).run()

View file

@ -31,16 +31,16 @@ import sys, transaction
# Check that job.py is called with the right parameters. # Check that job.py is called with the right parameters.
if len(sys.argv) != 2: if len(sys.argv) != 2:
print 'job.py was called with wrong args.' print('job.py was called with wrong args.')
print __doc__ print(__doc__)
else: else:
commands = sys.argv[1].split(';') commands = sys.argv[1].split(';')
# Check that every command has the right number of sub-elelements. # Check that every command has the right number of sub-elelements.
for command in commands: for command in commands:
parts = command.split(':') parts = command.split(':')
if len(parts) not in (4,5): if len(parts) not in (4,5):
print 'job.py was called with wrong args.' print('job.py was called with wrong args.')
print __doc__ print(__doc__)
for command in commands: for command in commands:
parts = command.split(':') parts = command.split(':')

View file

@ -141,7 +141,7 @@ class ZopeInstanceCreator:
os.chmod('inituser', 0644) os.chmod('inituser', 0644)
# User "zope" must own this instance # User "zope" must own this instance
os.system('chown -R zope %s' % self.instancePath) os.system('chown -R zope %s' % self.instancePath)
print 'Zope instance created in %s.' % self.instancePath print('Zope instance created in %s.' % self.instancePath)
os.chdir(curdir) os.chdir(curdir)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
@ -320,13 +320,13 @@ class NewScript:
# For Plone4, we will call it later. # For Plone4, we will call it later.
cmd = '%s %s -d %s' % (pythonPath, makeInstancePath, self.instancePath) cmd = '%s %s -d %s' % (pythonPath, makeInstancePath, self.instancePath)
if self.ploneVersion != 'plone4': if self.ploneVersion != 'plone4':
print cmd print(cmd)
os.system(cmd) os.system(cmd)
# Now, make the instance Plone-ready # Now, make the instance Plone-ready
action = 'Copying' action = 'Copying'
if linksForProducts: if linksForProducts:
action = 'Symlinking' action = 'Symlinking'
print '%s Plone stuff in the Zope instance...' % action print('%s Plone stuff in the Zope instance...' % action)
if self.ploneVersion in ('plone25', 'plone30'): if self.ploneVersion in ('plone25', 'plone30'):
self.installPlone25or30Stuff(linksForProducts) self.installPlone25or30Stuff(linksForProducts)
elif self.ploneVersion in ('plone3x', 'plone4'): elif self.ploneVersion in ('plone3x', 'plone4'):
@ -338,7 +338,7 @@ class NewScript:
os.environ['PYTHONPATH'] = '%s:%s' % \ os.environ['PYTHONPATH'] = '%s:%s' % \
(j(self.instancePath,'Products'), (j(self.instancePath,'Products'),
j(self.instancePath, 'lib/python')) j(self.instancePath, 'lib/python'))
print cmd print(cmd)
os.system(cmd) os.system(cmd)
self.patchPlone4(versions) self.patchPlone4(versions)
# Remove .bat files under Linux # Remove .bat files under Linux
@ -379,13 +379,12 @@ class NewScript:
try: try:
self.manageArgs(args) self.manageArgs(args)
if self.ploneVersion != 'zope': if self.ploneVersion != 'zope':
print 'Creating new %s instance...' % self.ploneVersion print('Creating new %s instance...' % self.ploneVersion)
self.createInstance(linksForProducts) self.createInstance(linksForProducts)
else: else:
ZopeInstanceCreator(self.instancePath).run() ZopeInstanceCreator(self.instancePath).run()
except NewError, ne: except NewError, ne:
optParser.print_help() optParser.print_help()
print
sys.stderr.write(str(ne)) sys.stderr.write(str(ne))
sys.stderr.write('\n') sys.stderr.write('\n')
sys.exit(ERROR_CODE) sys.exit(ERROR_CODE)

View file

@ -52,7 +52,7 @@ class OdfGrep:
# Run "grep" in this folder # Run "grep" in this folder
match = self.callGrep(tempFolder) match = self.callGrep(tempFolder)
if match: if match:
print 'Found in', fileName print('Found in %s' % fileName)
FolderDeleter.delete(tempFolder) FolderDeleter.delete(tempFolder)
def run(self): def run(self):
@ -65,12 +65,12 @@ class OdfGrep:
if os.path.splitext(name)[1] in self.toUnzip: if os.path.splitext(name)[1] in self.toUnzip:
self.grepFile(os.path.join(dir, name)) self.grepFile(os.path.join(dir, name))
else: else:
print '%s does not exist.' % self.fileOrFolder print('%s does not exist.' % self.fileOrFolder)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
if __name__ == '__main__': if __name__ == '__main__':
if len(sys.argv) != 3: if len(sys.argv) != 3:
print usage print(usage)
sys.exit() sys.exit()
OdfGrep(sys.argv[1], sys.argv[2]).run() OdfGrep(sys.argv[1], sys.argv[2]).run()
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------

View file

@ -28,9 +28,9 @@ recursive-include appy/pod *
recursive-include appy/shared * recursive-include appy/shared *
''' '''
def askLogin(): def askLogin():
print 'Login: ', print('Login:')
login = sys.stdin.readline().strip() login = sys.stdin.readline().strip()
print 'Password: ', print('Password:')
passwd = sys.stdin.readline().strip() passwd = sys.stdin.readline().strip()
return (login, passwd) return (login, passwd)
@ -84,7 +84,8 @@ class FtpFolder:
def clean(self, site): def clean(self, site):
'''Cleans this folder''' '''Cleans this folder'''
# First, clean subFolders if they exist # First, clean subFolders if they exist
print 'Cleaning', self.getFullName(), len(self.subFolders), 'subFolders' print('Cleaning %s %d subFolders' % \
(self.getFullName(), len(self.subFolders)))
for subFolder in self.subFolders: for subFolder in self.subFolders:
subFolder.clean(site) subFolder.clean(site)
# Remove the subFolder # Remove the subFolder
@ -93,7 +94,7 @@ class FtpFolder:
for f in self.files: for f in self.files:
fileName = '%s/%s' % (self.getFullName(), f) fileName = '%s/%s' % (self.getFullName(), f)
site.delete(fileName) site.delete(fileName)
print fileName, 'removed.' print('%s removed.' % fileName)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
class AppySite: class AppySite:
@ -146,17 +147,17 @@ class AppySite:
fileExt = os.path.splitext(fileName)[1] fileExt = os.path.splitext(fileName)[1]
if fileExt in self.textExtensions: if fileExt in self.textExtensions:
# Make a transfer in text mode # Make a transfer in text mode
print 'Transfer file %s (text mode)' % fileName print('Transfer file %s (text mode)' % fileName)
self.site.storlines(cmd, localFile) self.site.storlines(cmd, localFile)
else: else:
# Make a transfer in binary mode # Make a transfer in binary mode
print 'Transfer file %s (binary mode)' % fileName print('Transfer file %s (binary mode)' % fileName)
self.site.storbinary(cmd, localFile) self.site.storbinary(cmd, localFile)
def publish(self): def publish(self):
# Delete the existing content of the distant site # Delete the existing content of the distant site
self.createFolderProxies() self.createFolderProxies()
print 'Removing existing data on site...' print('Removing existing data on site...')
self.rootFolder.clean(self.site) self.rootFolder.clean(self.site)
curDir = os.getcwd() curDir = os.getcwd()
os.chdir('%s/temp' % appyPath) os.chdir('%s/temp' % appyPath)
@ -255,7 +256,7 @@ class Publisher:
yesNo = '[Y/n]' yesNo = '[Y/n]'
else: else:
yesNo = '[y/N]' yesNo = '[y/N]'
print question + ' ' + yesNo + ' ', print(question + ' ' + yesNo + ' ')
response = sys.stdin.readline().strip().lower() response = sys.stdin.readline().strip().lower()
res = False res = False
if response in ('y', 'yes'): if response in ('y', 'yes'):
@ -272,7 +273,7 @@ class Publisher:
def executeCommand(self, cmd): def executeCommand(self, cmd):
'''Executes the system command p_cmd.''' '''Executes the system command p_cmd.'''
print 'Executing %s...' % cmd print('Executing %s...' % cmd)
os.system(cmd) os.system(cmd)
distExcluded = ('appy/doc', 'appy/temp', 'appy/versions', 'appy/gen/test') distExcluded = ('appy/doc', 'appy/temp', 'appy/versions', 'appy/gen/test')
@ -336,9 +337,9 @@ class Publisher:
if os.path.exists(newZipRelease): if os.path.exists(newZipRelease):
if not self.askQuestion('"%s" already exists. Replace it?' % \ if not self.askQuestion('"%s" already exists. Replace it?' % \
newZipRelease, default='yes'): newZipRelease, default='yes'):
print 'Publication canceled.' print('Publication canceled.')
sys.exit(1) sys.exit(1)
print 'Removing obsolete %s...' % newZipRelease print('Removing obsolete %s...' % newZipRelease)
os.remove(newZipRelease) os.remove(newZipRelease)
zipFile = zipfile.ZipFile(newZipRelease, 'w', zipfile.ZIP_DEFLATED) zipFile = zipfile.ZipFile(newZipRelease, 'w', zipfile.ZIP_DEFLATED)
curdir = os.getcwd() curdir = os.getcwd()
@ -472,7 +473,7 @@ class Publisher:
if minimalist: if minimalist:
FolderDeleter.delete('%s/pod/test' % genSrcFolder) FolderDeleter.delete('%s/pod/test' % genSrcFolder)
# Write the appy version into the code itself (in appy/version.py)''' # Write the appy version into the code itself (in appy/version.py)'''
print 'Publishing version %s...' % self.versionShort print('Publishing version %s...' % self.versionShort)
# Dump version info in appy/version.py # Dump version info in appy/version.py
f = file('%s/version.py' % genSrcFolder, 'w') f = file('%s/version.py' % genSrcFolder, 'w')
f.write('short = "%s"\n' % self.versionShort) f.write('short = "%s"\n' % self.versionShort)
@ -493,7 +494,7 @@ class Publisher:
Cleaner().run(verbose=False) Cleaner().run(verbose=False)
# Perform a small analysis on the Appy code # Perform a small analysis on the Appy code
LinesCounter(appy).run() LinesCounter(appy).run()
print 'Generating site in %s...' % self.genFolder print('Generating site in %s...' % self.genFolder)
minimalist = self.askQuestion('Minimalist (shipped without tests)?', minimalist = self.askQuestion('Minimalist (shipped without tests)?',
default='no') default='no')
self.prepareGenFolder(minimalist) self.prepareGenFolder(minimalist)

View file

@ -21,10 +21,10 @@ class ZodbRestorer:
datePart = '-D %s' % self.restoreDate datePart = '-D %s' % self.restoreDate
repozoCmd = '%s %s -Rv -r %s %s -o %s' % (self.python, repozoCmd = '%s %s -Rv -r %s %s -o %s' % (self.python,
self.repozo, self.backupFolder, datePart, self.storageLocation) self.repozo, self.backupFolder, datePart, self.storageLocation)
print 'Executing %s...' % repozoCmd print('Executing %s...' % repozoCmd)
os.system(repozoCmd) os.system(repozoCmd)
stopTime = time.time() stopTime = time.time()
print 'Done in %d minutes.' % ((stopTime-startTime)/60) print('Done in %d minute(s).' % ((stopTime-startTime)/60))
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
class ZodbRestoreScript: class ZodbRestoreScript:

View file

@ -8,29 +8,29 @@ class Zipper:
def __init__(self): def __init__(self):
self.zipFileName = '%s/Desktop/appy.zip' % os.environ['HOME'] self.zipFileName = '%s/Desktop/appy.zip' % os.environ['HOME']
def createZipFile(self): def createZipFile(self):
print 'Creating %s...' % self.zipFileName print('Creating %s...' % self.zipFileName)
zipFile = zipfile.ZipFile(self.zipFileName, 'w', zipfile.ZIP_DEFLATED) zipFile = zipfile.ZipFile(self.zipFileName, 'w', zipfile.ZIP_DEFLATED)
for dir, dirnames, filenames in os.walk(appyPath): for dir, dirnames, filenames in os.walk(appyPath):
for f in filenames: for f in filenames:
fileName = os.path.join(dir, f) fileName = os.path.join(dir, f)
arcName = fileName[fileName.find('appy/'):] arcName = fileName[fileName.find('appy/'):]
print 'Adding %s' % fileName print('Adding %s' % fileName)
zipFile.write(fileName, arcName) zipFile.write(fileName, arcName)
zipFile.close() zipFile.close()
def run(self): def run(self):
# Where to put the zip file ? # Where to put the zip file ?
print "Where do you want to put appy.zip ? [Default is %s] " % \ print("Where do you want to put appy.zip ? [Default is %s] " % \
os.path.dirname(self.zipFileName), os.path.dirname(self.zipFileName))
response = sys.stdin.readline().strip() response = sys.stdin.readline().strip()
if response: if response:
if os.path.exists(response) and os.path.isdir(response): if os.path.exists(response) and os.path.isdir(response):
self.zipFileName = '%s/appy.zip' % response self.zipFileName = '%s/appy.zip' % response
else: else:
print '%s is not a folder.' % response print('%s is not a folder.' % response)
sys.exit(1) sys.exit(1)
if os.path.exists(self.zipFileName): if os.path.exists(self.zipFileName):
print 'Removing existing %s...' % self.zipFileName print('Removing existing %s...' % self.zipFileName)
os.remove(self.zipFileName) os.remove(self.zipFileName)
Cleaner().run(verbose=False) Cleaner().run(verbose=False)
self.createZipFile() self.createZipFile()

View file

@ -9,7 +9,7 @@ class ZopeRunner:
def run(self): def run(self):
# Check that an arg has been given (start, stop, fg, run) # Check that an arg has been given (start, stop, fg, run)
if not sys.argv[3].strip(): if not sys.argv[3].strip():
print 'Argument required.' print('Argument required.')
sys.exit(-1) sys.exit(-1)
# Identify the name of the application for which Zope must run. # Identify the name of the application for which Zope must run.
app = os.path.splitext(os.path.basename(sys.argv[2]))[0].lower() app = os.path.splitext(os.path.basename(sys.argv[2]))[0].lower()

View file

@ -230,8 +230,8 @@ class ClassDescriptor(Descriptor):
'''Adds a new field to the Tool.''' '''Adds a new field to the Tool.'''
exec "self.modelClass.%s = fieldType" % fieldName exec "self.modelClass.%s = fieldType" % fieldName
if fieldName in self.modelClass._appy_attributes: if fieldName in self.modelClass._appy_attributes:
print 'Warning, field "%s" is already existing on class "%s"' % \ print('Warning, field "%s" is already existing on class "%s"' % \
(fieldName, self.modelClass.__name__) (fieldName, self.modelClass.__name__))
return return
self.modelClass._appy_attributes.append(fieldName) self.modelClass._appy_attributes.append(fieldName)
self.orderedAttributes.append(fieldName) self.orderedAttributes.append(fieldName)

View file

@ -342,7 +342,7 @@ class Generator:
msg = '' msg = ''
if self.totalNumberOfTests: if self.totalNumberOfTests:
msg = ' (number of tests found: %d)' % self.totalNumberOfTests msg = ' (number of tests found: %d)' % self.totalNumberOfTests
print 'Done%s.' % msg print('Done%s.' % msg)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
class ZopeGenerator(Generator): class ZopeGenerator(Generator):
@ -427,8 +427,8 @@ class ZopeGenerator(Generator):
removedLabels = potFile.update(self.labels.get(),self.options.i18nClean, removedLabels = potFile.update(self.labels.get(),self.options.i18nClean,
not self.options.i18nSort) not self.options.i18nSort)
if removedLabels: if removedLabels:
print 'Warning: %d messages were removed from translation ' \ print('Warning: %d messages were removed from translation ' \
'files: %s' % (len(removedLabels), str(removedLabels)) 'files: %s' % (len(removedLabels), str(removedLabels)))
# Before generating the POT file, we still need to add one label for # Before generating the POT file, we still need to add one label for
# every page for the Translation class. We've not done it yet because # every page for the Translation class. We've not done it yet because
# the number of pages depends on the total number of labels in the POT # the number of pages depends on the total number of labels in the POT
@ -754,7 +754,7 @@ class ZopeGenerator(Generator):
'''Is called each time an Appy class is found in the application, for '''Is called each time an Appy class is found in the application, for
generating the corresponding Archetype class.''' generating the corresponding Archetype class.'''
k = classDescr.klass k = classDescr.klass
print 'Generating %s.%s (gen-class)...' % (k.__module__, k.__name__) print('Generating %s.%s (gen-class)...' % (k.__module__, k.__name__))
# Determine base Zope class # Determine base Zope class
isFolder = classDescr.isFolder() isFolder = classDescr.isFolder()
baseClass = isFolder and 'Folder' or 'SimpleItem' baseClass = isFolder and 'Folder' or 'SimpleItem'
@ -788,7 +788,7 @@ class ZopeGenerator(Generator):
'''This method creates the i18n labels related to the workflow described '''This method creates the i18n labels related to the workflow described
by p_wfDescr.''' by p_wfDescr.'''
k = wfDescr.klass k = wfDescr.klass
print 'Generating %s.%s (gen-workflow)...' % (k.__module__, k.__name__) print('Generating %s.%s (gen-workflow)...' % (k.__module__, k.__name__))
# Identify workflow name # Identify workflow name
wfName = WorkflowDescriptor.getWorkflowName(wfDescr.klass) wfName = WorkflowDescriptor.getWorkflowName(wfDescr.klass)
# Add i18n messages for states # Add i18n messages for states

View file

@ -15,9 +15,9 @@ if covFolder:
cov = coverage() cov = coverage()
cov.start() cov.start()
except ImportError: except ImportError:
print 'COVERAGE KO! The "coverage" program is not installed. You can ' \ print('COVERAGE KO! The "coverage" program is not installed. You can ' \
'download it from http://nedbatchelder.com/code/coverage.' \ 'download it from http://nedbatchelder.com/code/coverage.' \
'\nHit <enter> to execute the test suite without coverage.' '\nHit <enter> to execute the test suite without coverage.')
sys.stdin.readline() sys.stdin.readline()
def countTest(): def countTest():

View file

@ -31,6 +31,7 @@ XHTML_UNSTYLABLE_TAGS = XHTML_LISTS + ('li', 'a')
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
class PodError(Exception): class PodError(Exception):
@staticmethod
def dumpTraceback(buffer, tb, textNs, removeFirstLine): def dumpTraceback(buffer, tb, textNs, removeFirstLine):
if removeFirstLine: if removeFirstLine:
# This error came from an exception raised by pod. The text of the # This error came from an exception raised by pod. The text of the
@ -46,11 +47,13 @@ class PodError(Exception):
buffer.write('<%s:p>' % textNs) buffer.write('<%s:p>' % textNs)
try: try:
buffer.dumpContent(tLine) buffer.dumpContent(tLine)
except UnicodeDecodeError, ude: except UnicodeDecodeError:
buffer.dumpContent(tLine.decode('utf-8')) buffer.dumpContent(tLine.decode('utf-8'))
buffer.write('</%s:p>' % textNs) buffer.write('</%s:p>' % textNs)
dumpTraceback = staticmethod(dumpTraceback)
def dump(buffer, message, withinElement=None, removeFirstLine=False, dumpTb=True): @staticmethod
def dump(buffer, message, withinElement=None, removeFirstLine=False,
dumpTb=True):
'''Dumps the error p_message in p_buffer.''' '''Dumps the error p_message in p_buffer.'''
# Define some handful shortcuts # Define some handful shortcuts
e = buffer.env e = buffer.env
@ -80,7 +83,6 @@ class PodError(Exception):
for subTag in subTags: for subTag in subTags:
buffer.write('</%s>' % subTag.elem) buffer.write('</%s>' % subTag.elem)
buffer.write('</%s>' % withinElement.OD.elem) buffer.write('</%s>' % withinElement.OD.elem)
dump = staticmethod(dump)
# XXX To remove, present for backward compatibility only. # XXX To remove, present for backward compatibility only.
convertToXhtml = escapeXhtml convertToXhtml = escapeXhtml

View file

@ -491,7 +491,7 @@ class Renderer:
# an ODT or ODS to return to the user. So we produce a warning # an ODT or ODS to return to the user. So we produce a warning
# instead of raising an error. # instead of raising an error.
if (resultType in self.templateTypes) and self.forceOoCall: if (resultType in self.templateTypes) and self.forceOoCall:
print WARNING_INCOMPLETE_OD % str(pe) print(WARNING_INCOMPLETE_OD % str(pe))
else: else:
raise pe raise pe
return loOutput return loOutput
@ -535,7 +535,7 @@ class Renderer:
try: try:
self.finalizeFunction(self.unzipFolder) self.finalizeFunction(self.unzipFolder)
except Exception, e: except Exception, e:
print WARNING_FINALIZE_ERROR % str(e) print(WARNING_FINALIZE_ERROR % str(e))
# Re-zip the result, first as an OpenDocument file of the same type as # Re-zip the result, first as an OpenDocument file of the same type as
# the POD template (odt, ods...) # the POD template (odt, ods...)
resultExt = self.getTemplateType() resultExt = self.getTemplateType()

View file

@ -134,7 +134,7 @@ class Test(appy.shared.test.Test):
#tempFolder2 = '%s/sevResults' % self.testFolder #tempFolder2 = '%s/sevResults' % self.testFolder
#if not os.path.exists(tempFolder2): #if not os.path.exists(tempFolder2):
# os.mkdir(tempFolder2) # os.mkdir(tempFolder2)
#print 'Result is', self.result, 'temp folder 2 is', tempFolder2 #print('Result is %s, temp folder 2 is %s.' % (self.result,tempFolder2))
#shutil.copy(self.result, tempFolder2) #shutil.copy(self.result, tempFolder2)
def getOdtContent(self, odtFile): def getOdtContent(self, odtFile):

View file

@ -333,7 +333,7 @@ class TableParser:
if self.specialChars.has_key(specialChar): if self.specialChars.has_key(specialChar):
self.contentBuffer.write(self.specialChars[specialChar]) self.contentBuffer.write(self.specialChars[specialChar])
else: else:
print 'Warning: char %d not known.' % specialChar print('Warning: char %d not known.' % specialChar)
self.state = TableParser.READING_CONTENT self.state = TableParser.READING_CONTENT
def bufferize(self, char): def bufferize(self, char):
if self.state == TableParser.READING_CONTROL_WORD: if self.state == TableParser.READING_CONTROL_WORD:
@ -497,7 +497,6 @@ class RtfTablesParser:
if __name__ =='__main__': if __name__ =='__main__':
tables = RtfTablesParser("Tests.rtf").parse() tables = RtfTablesParser("Tests.rtf").parse()
for key, item in tables.iteritems(): for key, item in tables.iteritems():
print 'Table %s' % key print('Table %s' % key)
print item print(item)
print
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------

View file

@ -71,7 +71,7 @@ class TestReport:
raise InternalError(TEST_REPORT_SINGLETON_ERROR) raise InternalError(TEST_REPORT_SINGLETON_ERROR)
def say(self, msg, force=False, encoding=None): def say(self, msg, force=False, encoding=None):
if self.verbose or force: if self.verbose or force:
print msg print(msg)
if encoding: if encoding:
self.report.write(msg.encode(encoding)) self.report.write(msg.encode(encoding))
else: else:

View file

@ -40,7 +40,7 @@ def cleanFolder(folder, exts=extsToClean, folders=(), verbose=False):
'''This function allows to remove, in p_folder and subfolders, any file '''This function allows to remove, in p_folder and subfolders, any file
whose extension is in p_exts, and any folder whose name is in whose extension is in p_exts, and any folder whose name is in
p_folders.''' p_folders.'''
if verbose: print 'Cleaning folder', folder, '...' if verbose: print('Cleaning folder %s...' % folder)
# Remove files with an extension listed in p_exts # Remove files with an extension listed in p_exts
if exts: if exts:
for root, dirs, files in os.walk(folder): for root, dirs, files in os.walk(folder):
@ -48,7 +48,7 @@ def cleanFolder(folder, exts=extsToClean, folders=(), verbose=False):
ext = os.path.splitext(fileName)[1] ext = os.path.splitext(fileName)[1]
if (ext in exts) or ext.endswith('~'): if (ext in exts) or ext.endswith('~'):
fileToRemove = os.path.join(root, fileName) fileToRemove = os.path.join(root, fileName)
if verbose: print 'Removing file %s...' % fileToRemove if verbose: print('Removing file %s...' % fileToRemove)
os.remove(fileToRemove) os.remove(fileToRemove)
# Remove folders whose names are in p_folders. # Remove folders whose names are in p_folders.
if folders: if folders:
@ -56,7 +56,7 @@ def cleanFolder(folder, exts=extsToClean, folders=(), verbose=False):
for folderName in dirs: for folderName in dirs:
if folderName in folders: if folderName in folders:
toDelete = os.path.join(root, folderName) toDelete = os.path.join(root, folderName)
if verbose: print 'Removing folder %s...' % toDelete if verbose: print('Removing folder %s...' % toDelete)
FolderDeleter.delete(toDelete) FolderDeleter.delete(toDelete)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
@ -393,8 +393,8 @@ class CodeAnalysis:
if not lines: return if not lines: return
commentRate = (self.commentLines / float(lines)) * 100.0 commentRate = (self.commentLines / float(lines)) * 100.0
blankRate = (self.emptyLines / float(lines)) * 100.0 blankRate = (self.emptyLines / float(lines)) * 100.0
print '%s: %d files, %d lines (%.0f%% comments, %.0f%% blank)' % \ print('%s: %d files, %d lines (%.0f%% comments, %.0f%% blank)' % \
(self.name, self.numberOfFiles, lines, commentRate, blankRate) (self.name, self.numberOfFiles, lines, commentRate, blankRate))
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
class LinesCounter: class LinesCounter:

View file

@ -214,10 +214,10 @@ class XmlParser(ContentHandler, ErrorHandler):
# ErrorHandler methods --------------------------------------------------- # ErrorHandler methods ---------------------------------------------------
def error(self, error): def error(self, error):
if self.raiseOnError: raise error if self.raiseOnError: raise error
else: print 'SAX error', error else: print('SAX error %s' % str(error))
def fatalError(self, error): def fatalError(self, error):
if self.raiseOnError: raise error if self.raiseOnError: raise error
else: print 'SAX fatal error', error else: print('SAX fatal error %s' % str(error))
def warning(self, error): pass def warning(self, error): pass
def parse(self, xml, source='string'): def parse(self, xml, source='string'):
@ -940,17 +940,17 @@ class XmlComparator:
msg = 'Difference(s) detected between files %s and %s:' % \ msg = 'Difference(s) detected between files %s and %s:' % \
(self.fileNameA, self.fileNameB) (self.fileNameA, self.fileNameB)
if report: report.say(msg, encoding='utf-8') if report: report.say(msg, encoding='utf-8')
else: print msg else: print(msg)
atLeastOneDiff = True atLeastOneDiff = True
if not lastLinePrinted: if not lastLinePrinted:
if report: report.say('...') if report: report.say('...')
else: print '...' else: print('...')
if self.areXml: if self.areXml:
if report: report.say(line, encoding=encoding) if report: report.say(line, encoding=encoding)
else: print line else: print(line)
else: else:
if report: report.say(line[:-1], encoding=encoding) if report: report.say(line[:-1], encoding=encoding)
else: print line[:-1] else: print(line[:-1])
lastLinePrinted = True lastLinePrinted = True
else: else:
lastLinePrinted = False lastLinePrinted = False