[CalendarServer-changes] [10813] CalendarServer/trunk

source_changes at macosforge.org source_changes at macosforge.org
Tue Feb 26 12:09:34 PST 2013


Revision: 10813
          http://trac.calendarserver.org//changeset/10813
Author:   wsanchez at apple.com
Date:     2013-02-26 12:09:34 -0800 (Tue, 26 Feb 2013)
Log Message:
-----------
use print function

Modified Paths:
--------------
    CalendarServer/trunk/calendarserver/platform/darwin/od/dsquery.py
    CalendarServer/trunk/calendarserver/platform/darwin/od/setup_directory.py
    CalendarServer/trunk/calendarserver/platform/darwin/od/setup_testusers.py
    CalendarServer/trunk/calendarserver/platform/darwin/od/test/test_opendirectory.py
    CalendarServer/trunk/calendarserver/tap/caldav.py
    CalendarServer/trunk/calendarserver/tools/ampnotifications.py
    CalendarServer/trunk/calendarserver/tools/anonymize.py
    CalendarServer/trunk/calendarserver/tools/backup_pg.py
    CalendarServer/trunk/calendarserver/tools/bootstrapdatabase.py
    CalendarServer/trunk/calendarserver/tools/calverify.py
    CalendarServer/trunk/calendarserver/tools/calverify_diff.py
    CalendarServer/trunk/calendarserver/tools/changeip_calendar.py
    CalendarServer/trunk/calendarserver/tools/config.py
    CalendarServer/trunk/calendarserver/tools/dbinspect.py
    CalendarServer/trunk/calendarserver/tools/dkimtool.py
    CalendarServer/trunk/calendarserver/tools/doublequotefix.py
    CalendarServer/trunk/calendarserver/tools/export.py
    CalendarServer/trunk/calendarserver/tools/fixcalendardata.py
    CalendarServer/trunk/calendarserver/tools/gateway.py
    CalendarServer/trunk/calendarserver/tools/icalsplit.py
    CalendarServer/trunk/calendarserver/tools/loadaugmentdb.py
    CalendarServer/trunk/calendarserver/tools/managepostgres.py
    CalendarServer/trunk/calendarserver/tools/managetimezones.py
    CalendarServer/trunk/calendarserver/tools/migrate.py
    CalendarServer/trunk/calendarserver/tools/migrate_verify.py
    CalendarServer/trunk/calendarserver/tools/notifications.py
    CalendarServer/trunk/calendarserver/tools/obliterate.py
    CalendarServer/trunk/calendarserver/tools/principals.py
    CalendarServer/trunk/calendarserver/tools/purge.py
    CalendarServer/trunk/calendarserver/tools/push.py
    CalendarServer/trunk/calendarserver/tools/resources.py
    CalendarServer/trunk/calendarserver/tools/shell/terminal.py
    CalendarServer/trunk/calendarserver/tools/test/test_calverify.py
    CalendarServer/trunk/calendarserver/tools/test/test_gateway.py
    CalendarServer/trunk/calendarserver/tools/upgrade.py
    CalendarServer/trunk/calendarserver/tools/validcalendardata.py
    CalendarServer/trunk/contrib/migration/calendarcommonextra.py
    CalendarServer/trunk/contrib/migration/calendardemotion.py
    CalendarServer/trunk/contrib/migration/calendarmigrator.py
    CalendarServer/trunk/contrib/migration/calendarpromotion.py
    CalendarServer/trunk/contrib/migration/test/test_migrator.py
    CalendarServer/trunk/contrib/performance/benchlib.py
    CalendarServer/trunk/contrib/performance/benchmark.py
    CalendarServer/trunk/contrib/performance/compare.py
    CalendarServer/trunk/contrib/performance/display-calendar-events.py
    CalendarServer/trunk/contrib/performance/httpauth.py
    CalendarServer/trunk/contrib/performance/loadtest/ampsim.py
    CalendarServer/trunk/contrib/performance/loadtest/ical.py
    CalendarServer/trunk/contrib/performance/loadtest/population.py
    CalendarServer/trunk/contrib/performance/loadtest/sim.py
    CalendarServer/trunk/contrib/performance/massupload.py
    CalendarServer/trunk/contrib/performance/report.py
    CalendarServer/trunk/contrib/performance/sqlusage/sqlusage.py
    CalendarServer/trunk/contrib/performance/sqlwatch.py
    CalendarServer/trunk/contrib/performance/stats.py
    CalendarServer/trunk/contrib/performance/upload.py
    CalendarServer/trunk/contrib/tools/anonymous_log.py
    CalendarServer/trunk/contrib/tools/dtraceanalyze.py
    CalendarServer/trunk/contrib/tools/fakecalendardata.py
    CalendarServer/trunk/contrib/tools/harpoon.py
    CalendarServer/trunk/contrib/tools/monitoranalysis.py
    CalendarServer/trunk/contrib/tools/monitorsplit.py
    CalendarServer/trunk/contrib/tools/netstatus.py
    CalendarServer/trunk/contrib/tools/pg_stats_analysis.py
    CalendarServer/trunk/contrib/tools/protocolanalysis.py
    CalendarServer/trunk/contrib/tools/readStats.py
    CalendarServer/trunk/contrib/tools/request_monitor.py
    CalendarServer/trunk/contrib/tools/sortrecurrences.py
    CalendarServer/trunk/contrib/tools/sqldata_from_path.py
    CalendarServer/trunk/setup.py
    CalendarServer/trunk/support/version.py
    CalendarServer/trunk/test
    CalendarServer/trunk/twext/enterprise/dal/parseschema.py
    CalendarServer/trunk/twext/internet/gaiendpoint.py
    CalendarServer/trunk/twext/python/_plistlib.py
    CalendarServer/trunk/twext/python/log.py
    CalendarServer/trunk/twext/python/memcacheclient.py
    CalendarServer/trunk/twext/web2/dav/resource.py
    CalendarServer/trunk/twext/web2/fileupload.py
    CalendarServer/trunk/twext/web2/http_headers.py
    CalendarServer/trunk/twext/web2/server.py
    CalendarServer/trunk/twext/web2/test/test_client.py
    CalendarServer/trunk/twistedcaldav/backup.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_guidchange.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_ldapdirectory.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_livedirectory.py
    CalendarServer/trunk/twistedcaldav/directory/test/test_principal.py
    CalendarServer/trunk/twistedcaldav/extensions.py
    CalendarServer/trunk/twistedcaldav/localization.py
    CalendarServer/trunk/twistedcaldav/query/expression.py
    CalendarServer/trunk/twistedcaldav/query/sqlgenerator.py
    CalendarServer/trunk/twistedcaldav/scheduling/imip/test/test_outbound.py
    CalendarServer/trunk/twistedcaldav/scheduling/test/test_itip.py
    CalendarServer/trunk/twistedcaldav/test/util.py
    CalendarServer/trunk/txdav/base/datastore/file.py
    CalendarServer/trunk/txdav/common/datastore/test/util.py

Modified: CalendarServer/trunk/calendarserver/platform/darwin/od/dsquery.py
===================================================================
--- CalendarServer/trunk/calendarserver/platform/darwin/od/dsquery.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/platform/darwin/od/dsquery.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # limitations under the License.
 #
 ##
+from __future__ import print_function
 
 """
 Compound query builder. We do this in Python to avoid having to mess
@@ -130,5 +131,5 @@
     for expr, result in exprs:
         gen = expr.generate()
         if gen != result:
-            print "Generate expression %s != %s" % (gen, result,)
-    print "Done."
+            print("Generate expression %s != %s" % (gen, result,))
+    print("Done.")

Modified: CalendarServer/trunk/calendarserver/platform/darwin/od/setup_directory.py
===================================================================
--- CalendarServer/trunk/calendarserver/platform/darwin/od/setup_directory.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/platform/darwin/od/setup_directory.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 import sys
@@ -204,12 +205,12 @@
 
 def usage(e=None):
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] local_user local_password odmaster_user odmaster_password" % (name,)
-    print ""
-    print " Configures local and OD master directories for testing"
-    print ""
-    print "options:"
-    print " -h --help: print this help and exit"
+    print("usage: %s [options] local_user local_password odmaster_user odmaster_password" % (name,))
+    print("")
+    print(" Configures local and OD master directories for testing")
+    print("")
+    print("options:")
+    print(" -h --help: print this help and exit")
     if e:
         sys.exit(1)
     else:
@@ -246,7 +247,7 @@
         attrs,
         None)
     if error:
-        print error
+        print(error)
         raise ODError(error)
     return record
 
@@ -295,7 +296,7 @@
 
         node, error = odframework.ODNode.nodeWithSession_name_error_(session, nodeName, None)
         if error:
-            print error
+            print(error)
             raise ODError(error)
 
         result, error = node.setCredentialsWithRecordType_recordName_password_error_(
@@ -305,45 +306,45 @@
             None
         )
         if error:
-            print "Unable to authenticate with directory %s: %s" % (nodeName, error)
+            print("Unable to authenticate with directory %s: %s" % (nodeName, error))
             raise ODError(error)
 
-        print "Successfully authenticated with directory %s" % (nodeName,)
+        print("Successfully authenticated with directory %s" % (nodeName,))
 
-        print "Creating users within %s:" % (nodeName,)
+        print("Creating users within %s:" % (nodeName,))
         for recordName, attrs in users:
             record = lookupRecordName(node, dsattributes.kDSStdRecordTypeUsers, recordName)
             if record is None:
-                print "Creating user %s" % (recordName,)
+                print("Creating user %s" % (recordName,))
                 try:
                     record = createRecord(node, dsattributes.kDSStdRecordTypeUsers, recordName, attrs)
-                    print "Successfully created user %s" % (recordName,)
+                    print("Successfully created user %s" % (recordName,))
                     result, error = record.changePassword_toPassword_error_(
                         None, "password", None)
                     if error or not result:
-                        print "Failed to set password for %s: %s" % (recordName, error)
+                        print("Failed to set password for %s: %s" % (recordName, error))
                     else:
-                        print "Successfully set password for %s" % (recordName,)
+                        print("Successfully set password for %s" % (recordName,))
                 except ODError, e:
-                    print "Failed to create user %s: %s" % (recordName, e)
+                    print("Failed to create user %s: %s" % (recordName, e))
             else:
-                print "User %s already exists" % (recordName,)
+                print("User %s already exists" % (recordName,))
 
             if record is not None:
                 userRecords.append(record)
 
-        print "Creating groups within %s:" % (nodeName,)
+        print("Creating groups within %s:" % (nodeName,))
         for recordName, attrs in groups:
             record = lookupRecordName(node, dsattributes.kDSStdRecordTypeGroups, recordName)
             if record is None:
-                print "Creating group %s" % (recordName,)
+                print("Creating group %s" % (recordName,))
                 try:
                     record = createRecord(node, dsattributes.kDSStdRecordTypeGroups, recordName, attrs)
-                    print "Successfully created group %s" % (recordName,)
+                    print("Successfully created group %s" % (recordName,))
                 except ODError, e:
-                    print "Failed to create group %s: %s" % (recordName, e)
+                    print("Failed to create group %s: %s" % (recordName, e))
             else:
-                print "Group %s already exists" % (recordName,)
+                print("Group %s already exists" % (recordName,))
 
         print
 
@@ -359,18 +360,18 @@
         for saclGroupName in saclGroupNames:
             saclGroupRecord = lookupRecordName(node, dsattributes.kDSStdRecordTypeGroups, saclGroupName)
             if saclGroupRecord:
-                print "Populating %s SACL group:" % (saclGroupName,)
+                print("Populating %s SACL group:" % (saclGroupName,))
                 for userRecord in userRecords:
                     details, error = userRecord.recordDetailsForAttributes_error_(None, None)
                     recordName = details.get(dsattributes.kDSNAttrRecordName, [None])[0]
                     result, error = saclGroupRecord.isMemberRecord_error_(userRecord, None)
                     if result:
-                        print "%s is already in the %s SACL group" % (recordName, saclGroupName)
+                        print("%s is already in the %s SACL group" % (recordName, saclGroupName))
                     else:
                         result, error = saclGroupRecord.addMemberRecord_error_(userRecord, None)
-                        print "Adding %s to the %s SACL group" % (recordName, saclGroupName)
+                        print("Adding %s to the %s SACL group" % (recordName, saclGroupName))
 
-            print
+            print("")
 
 class ODError(Exception):
     def __init__(self, error):

Modified: CalendarServer/trunk/calendarserver/platform/darwin/od/setup_testusers.py
===================================================================
--- CalendarServer/trunk/calendarserver/platform/darwin/od/setup_testusers.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/platform/darwin/od/setup_testusers.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 import sys
@@ -23,12 +24,12 @@
 
 def usage(e=None):
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] local_user local_password" % (name,)
-    print ""
-    print " Configures local directory for test users"
-    print ""
-    print "options:"
-    print " -h --help: print this help and exit"
+    print("usage: %s [options] local_user local_password" % (name,))
+    print("")
+    print(" Configures local directory for test users")
+    print("")
+    print("options:")
+    print(" -h --help: print this help and exit")
     if e:
         sys.exit(1)
     else:
@@ -65,7 +66,7 @@
         attrs,
         None)
     if error:
-        print error
+        print(error)
         raise ODError(error)
     return record
 
@@ -90,7 +91,7 @@
     nodeName = "/Local/Default"
     node, error = odframework.ODNode.nodeWithSession_name_error_(session, nodeName, None)
     if error:
-        print error
+        print(error)
         raise ODError(error)
 
     result, error = node.setCredentialsWithRecordType_recordName_password_error_(
@@ -100,12 +101,12 @@
         None
     )
     if error:
-        print "Unable to authenticate with directory %s: %s" % (nodeName, error)
+        print("Unable to authenticate with directory %s: %s" % (nodeName, error))
         raise ODError(error)
 
-    print "Successfully authenticated with directory %s" % (nodeName,)
+    print("Successfully authenticated with directory %s" % (nodeName,))
 
-    print "Creating users within %s:" % (nodeName,)
+    print("Creating users within %s:" % (nodeName,))
     for i in xrange(99):
         j = i+1
         recordName = "user%02d" % (j,)
@@ -120,20 +121,20 @@
 
         record = lookupRecordName(node, dsattributes.kDSStdRecordTypeUsers, recordName)
         if record is None:
-            print "Creating user %s" % (recordName,)
+            print("Creating user %s" % (recordName,))
             try:
                 record = createRecord(node, dsattributes.kDSStdRecordTypeUsers, recordName, attrs)
-                print "Successfully created user %s" % (recordName,)
+                print("Successfully created user %s" % (recordName,))
                 result, error = record.changePassword_toPassword_error_(
                     None, password, None)
                 if error or not result:
-                    print "Failed to set password for %s: %s" % (recordName, error)
+                    print("Failed to set password for %s: %s" % (recordName, error))
                 else:
-                    print "Successfully set password for %s" % (recordName,)
+                    print("Successfully set password for %s" % (recordName,))
             except ODError, e:
-                print "Failed to create user %s: %s" % (recordName, e)
+                print("Failed to create user %s: %s" % (recordName, e))
         else:
-            print "User %s already exists" % (recordName,)
+            print("User %s already exists" % (recordName,))
 
 
 class ODError(Exception):

Modified: CalendarServer/trunk/calendarserver/platform/darwin/od/test/test_opendirectory.py
===================================================================
--- CalendarServer/trunk/calendarserver/platform/darwin/od/test/test_opendirectory.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/platform/darwin/od/test/test_opendirectory.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from twistedcaldav.test.util import TestCase
 import hashlib
@@ -41,10 +42,10 @@
     if "odtestalbert" in recordNames:
         runTests = True
     else:
-        print "Please run setup_directory.py to populate OD"
+        print("Please run setup_directory.py to populate OD")
 
 except ImportError:
-    print "Unable to import OpenDirectory framework"
+    print("Unable to import OpenDirectory framework")
 
 
 def generateNonce():

Modified: CalendarServer/trunk/calendarserver/tap/caldav.py
===================================================================
--- CalendarServer/trunk/calendarserver/tap/caldav.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tap/caldav.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 __all__ = [
     "CalDAVService",
@@ -366,7 +367,7 @@
             self.loadConfiguration()
             self.checkConfiguration()
         except ConfigurationError, e:
-            print "Invalid configuration: %s" % (e,)
+            print("Invalid configuration: %s" % (e,))
             sys.exit(1)
 
 
@@ -375,7 +376,7 @@
             raise ConfigurationError("Config file %s not found. Exiting."
                                      % (self["config"],))
 
-        print "Reading configuration from file: %s" % (self["config"],)
+        print("Reading configuration from file: %s" % (self["config"],))
 
         config.load(self["config"])
         config.updateDefaults(self.overrides)
@@ -390,7 +391,7 @@
         # Having CalDAV *and* CardDAV both disabled is an illegal configuration
         # for a running server (but is fine for command-line utilities)
         if not config.EnableCalDAV and not config.EnableCardDAV:
-            print "Neither EnableCalDAV nor EnableCardDAV are set to True."
+            print("Neither EnableCalDAV nor EnableCardDAV are set to True.")
             sys.exit(1)
 
         uid, gid = None, None
@@ -753,10 +754,10 @@
                     "passwd" : config.Manhole.PasswordFilePath,
                 })
                 manholeService.setServiceParent(result)
-                # Using print because logging isn't ready at this point
-                print "Manhole access enabled: %s" % (portString,)
+                # Using print(because logging isn't ready at this point)
+                print("Manhole access enabled: %s" % (portString,))
             except ImportError:
-                print "Manhole access could not enabled because manhole_tap could not be imported"
+                print("Manhole access could not enabled because manhole_tap could not be imported")
 
         return result
 
@@ -1323,10 +1324,10 @@
                     "passwd" : config.Manhole.PasswordFilePath,
                 })
                 manholeService.setServiceParent(s)
-                # Using print because logging isn't ready at this point
-                print "Manhole access enabled: %s" % (portString,)
+                # Using print(because logging isn't ready at this point)
+                print("Manhole access enabled: %s" % (portString,))
             except ImportError:
-                print "Manhole access could not enabled because manhole_tap could not be imported"
+                print("Manhole access could not enabled because manhole_tap could not be imported")
 
 
         # Finally, let's get the real show on the road.  Create a service that

Modified: CalendarServer/trunk/calendarserver/tools/ampnotifications.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/ampnotifications.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/ampnotifications.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.push.amppush import subscribeToIDs
 from calendarserver.tools.cmdline import utilityMain
@@ -34,17 +35,17 @@
 def usage(e=None):
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] [pushkey ...]" % (name,)
-    print ""
-    print "  Monitor AMP Push Notifications"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -p --port <port>: AMP port to connect to"
-    print "  -s --server <hostname>: AMP server to connect to"
-    print "  --debug: verbose logging"
-    print ""
+    print("usage: %s [options] [pushkey ...]" % (name,))
+    print("")
+    print("  Monitor AMP Push Notifications")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -p --port <port>: AMP port to connect to")
+    print("  -s --server <hostname>: AMP server to connect to")
+    print("  --debug: verbose logging")
+    print("")
 
     if e:
         sys.stderr.write("%s\n" % (e,))
@@ -141,13 +142,13 @@
 
 
 def notificationCallback(id, dataChangedTimestamp):
-    print "Received notification for:", id
+    print("Received notification for:", id)
     return succeed(True)
 
 
 
 @inlineCallbacks
 def monitorAMPNotifications(hostname, port, ids):
-    print "Subscribing to notifications..."
+    print("Subscribing to notifications...")
     yield subscribeToIDs(hostname, port, ids, notificationCallback)
-    print "Waiting for notifications..."
+    print("Waiting for notifications...")

Modified: CalendarServer/trunk/calendarserver/tools/anonymize.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/anonymize.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/anonymize.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,7 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
-
+from __future__ import print_function
 from __future__ import with_statement
 
 from getopt import getopt, GetoptError
@@ -47,20 +47,20 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] source destination" % (name,)
-    print ""
-    print "  Anonymizes calendar data"
-    print ""
-    print "  source and destination should refer to document root directories"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -n --node <node>: Directory node (defaults to /Search)"
-    print ""
+    print("usage: %s [options] source destination" % (name,))
+    print("")
+    print("  Anonymizes calendar data")
+    print("")
+    print("  source and destination should refer to document root directories")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -n --node <node>: Directory node (defaults to /Search)")
+    print("")
 
     if e:
         sys.exit(64)
@@ -110,14 +110,14 @@
 def anonymizeRoot(directoryMap, sourceDirectory, destDirectory):
     # sourceDirectory and destDirectory are DocumentRoots
 
-    print "Anonymizing calendar data from %s into %s" % (sourceDirectory, destDirectory)
+    print("Anonymizing calendar data from %s into %s" % (sourceDirectory, destDirectory))
 
     homes = 0
     calendars = 0
     resources = 0
 
     if not os.path.exists(sourceDirectory):
-        print "Can't find source: %s" % (sourceDirectory,)
+        print("Can't find source: %s" % (sourceDirectory,))
         sys.exit(1)
 
     if not os.path.exists(destDirectory):
@@ -147,7 +147,7 @@
                         for home in os.listdir(secondPath):
                             record = directoryMap.lookupCUA(home)
                             if not record:
-                                print "Couldn't find %s, skipping." % (home,)
+                                print("Couldn't find %s, skipping." % (home,))
                                 continue
                             sourceHome = os.path.join(secondPath, home)
                             destHome = os.path.join(destUidHomes,
@@ -162,13 +162,13 @@
                     continue
                 record = directoryMap.lookupCUA(home)
                 if not record:
-                    print "Couldn't find %s, skipping." % (home,)
+                    print("Couldn't find %s, skipping." % (home,))
                     continue
                 sourceHome = os.path.join(sourceUidHomes, home)
                 destHome = os.path.join(destUidHomes, record['guid'])
                 homeList.append((sourceHome, destHome, record))
 
-        print "Processing %d calendar homes..." % (len(homeList),)
+        print("Processing %d calendar homes..." % (len(homeList),))
 
         for sourceHome, destHome, record in homeList:
             quotaUsed = 0
@@ -268,23 +268,23 @@
             )
 
             if not (homes % 100):
-                print " %d..." % (homes,)
+                print(" %d..." % (homes,))
 
-    print "Done."
-    print ""
+    print("Done.")
+    print("")
 
-    print "Calendar totals:"
-    print " Calendar homes: %d" % (homes,)
-    print " Calendars: %d" % (calendars,)
-    print " Events: %d" % (resources,)
-    print ""
+    print("Calendar totals:")
+    print(" Calendar homes: %d" % (homes,))
+    print(" Calendars: %d" % (calendars,))
+    print(" Events: %d" % (resources,))
+    print("")
 
 
 def anonymizeData(directoryMap, data):
     try:
         pyobj = PyCalendar.parseText(data)
     except Exception, e:
-        print "Failed to parse (%s): %s" % (e, data)
+        print("Failed to parse (%s): %s" % (e, data))
         return None
 
     # Delete property from the top level
@@ -303,7 +303,7 @@
                     cua = prop.getValue().getValue()
                     record = directoryMap.lookupCUA(cua)
                     if record is None:
-                        # print "Can't find record for", cua
+                        # print("Can't find record for", cua)
                         record = directoryMap.addRecord(cua=cua)
                         if record is None:
                             comp.removeProperty(prop)
@@ -371,10 +371,10 @@
             'resources' : ('Resources', 'resource'),
         }
 
-        print "Fetching records from directory: %s" % (node,)
+        print("Fetching records from directory: %s" % (node,))
 
         for internalType, (recordType, friendlyType) in self.strings.iteritems():
-            print " %s..." % (internalType,)
+            print(" %s..." % (internalType,))
             child = Popen(
                 args = [
                     "/usr/bin/dscl", "-plist", node, "-readall",
@@ -402,8 +402,8 @@
                         names=origRecordNames, emails=origEmails,
                         members=origMembers)
 
-        print "Done."
-        print ""
+        print("Done.")
+        print("")
 
     def addRecord(self, internalType="users", guid=None, names=None,
         emails=None, members=None, cua=None):
@@ -450,7 +450,7 @@
                     name = urllib.quote(name).lower()
                     keys.append(name)
                 except:
-                    # print "Failed to urllib.quote( ) %s. Skipping." % (name,)
+                    # print("Failed to urllib.quote( ) %s. Skipping." % (name,))
                     pass
         if emails:
             for email in emails:
@@ -483,13 +483,13 @@
 
 
     def printStats(self):
-        print "Directory totals:"
+        print("Directory totals:")
         for internalType, (recordType, ignore) in self.strings.iteritems():
-            print " %s: %d" % (recordType, self.counts[internalType])
+            print(" %s: %d" % (recordType, self.counts[internalType]))
 
         unknown = self.counts['unknown']
         if unknown:
-            print " Principals not found in directory: %d" % (unknown,)
+            print(" Principals not found in directory: %d" % (unknown,))
 
     def dumpDsImports(self, dirPath):
         if not os.path.exists(dirPath):
@@ -587,7 +587,7 @@
         try:
             text = text.encode('utf-8')
         except UnicodeEncodeError:
-            print "Failed to anonymize:", text
+            print("Failed to anonymize:", text)
             text = "Anonymize me!"
     h = hashlib.md5(text)
     h = h.hexdigest()

Modified: CalendarServer/trunk/calendarserver/tools/backup_pg.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/backup_pg.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/backup_pg.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from getopt import getopt, GetoptError
 import os
@@ -38,19 +39,19 @@
 
 def usage(e=None):
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] command backup-file" % (name,)
-    print ""
-    print " Backup or restore calendar and addressbook data"
-    print ""
-    print "options:"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -h --help: print this help and exit"
-    print "  -v --verbose: print additional information"
-    print ""
-    print "commands:"
-    print "  backup: create backup-file in compressed tar format (tgz)"
-    print "  restore: restore from backup-file"
-    print ""
+    print("usage: %s [options] command backup-file" % (name,))
+    print("")
+    print(" Backup or restore calendar and addressbook data")
+    print("")
+    print("options:")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -h --help: print this help and exit")
+    print("  -v --verbose: print additional information")
+    print("")
+    print("commands:")
+    print("  backup: create backup-file in compressed tar format (tgz)")
+    print("  restore: restore from backup-file")
+    print("")
 
     if e:
         sys.stderr.write("%s\n" % (e,))
@@ -75,14 +76,14 @@
     ]
     try:
         if verbose:
-            print "\nDumping data to %s" % (dumpFile,)
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("\nDumping data to %s" % (dumpFile,))
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         raise BackupError(
             "%s failed:\n%s (exit code = %d)" %
             (PGDUMP, e.output, e.returncode)
@@ -102,14 +103,14 @@
     ]
     try:
         if verbose:
-            print "\nLoading data from %s" % (dumpFile,)
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("\nLoading data from %s" % (dumpFile,))
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         raise BackupError(
             "%s failed:\n%s (exit code = %d)" %
             (PSQL, e.output, e.returncode)
@@ -168,24 +169,24 @@
             dumpData(dumpPath, verbose=verbose)
 
             if verbose:
-                print "Creating %s" % (filename,)
+                print("Creating %s" % (filename,))
             tar = tarfile.open(filename, "w:gz")
 
             if verbose:
-                print "Adding %s" % (serverRoot,)
+                print("Adding %s" % (serverRoot,))
             tar.add(serverRoot)
 
             if not dataRoot.startswith(serverRoot):
                 # DataRoot is not contained within ServerRoot (i.e, it's on
                 # another volume)
                 if verbose:
-                    print "Adding %s" % (dataRoot,)
+                    print("Adding %s" % (dataRoot,))
                 tar.add(dataRoot)
 
             tar.close()
 
             if verbose:
-                print "Done"
+                print("Done")
         except BackupError, e:
             error("Failed to dump database; error: %s" % (e,))
 
@@ -195,13 +196,13 @@
             tar = tarfile.open(filename, "r:gz")
 
             if verbose:
-                print "Extracting from backup file: %s" % (filename,)
+                print("Extracting from backup file: %s" % (filename,))
             tar.extractall(path="/")
 
             loadData(dumpPath, verbose=verbose)
 
             if verbose:
-                print "Cleaning up database dump file: %s" % (dumpPath,)
+                print("Cleaning up database dump file: %s" % (dumpPath,))
             os.remove(dumpPath)
 
         except BackupError, e:

Modified: CalendarServer/trunk/calendarserver/tools/bootstrapdatabase.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/bootstrapdatabase.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/bootstrapdatabase.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from getopt import getopt, GetoptError
 import os
@@ -33,14 +34,14 @@
 
 def usage(e=None):
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] username" % (name,)
-    print ""
-    print " Bootstrap calendar server postgres database and schema"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -v --verbose: print additional information"
-    print ""
+    print("usage: %s [options] username" % (name,))
+    print("")
+    print(" Bootstrap calendar server postgres database and schema")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -v --verbose: print additional information")
+    print("")
 
     if e:
         sys.stderr.write("%s\n" % (e,))
@@ -66,15 +67,15 @@
     ]
     try:
         if verbose:
-            print "\nAttempting to create user..."
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("\nAttempting to create user...")
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
         return True
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         if "already exists" in e.output:
             return False
         raise BootstrapError(
@@ -98,15 +99,15 @@
     ]
     try:
         if verbose:
-            print "\nAttempting to create database..."
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("\nAttempting to create database...")
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
         return True
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         if "already exists" in e.output:
             return False
         raise BootstrapError(
@@ -131,14 +132,14 @@
     ]
     try:
         if verbose:
-            print "\nAttempting to read schema version..."
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("\nAttempting to read schema version...")
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         raise BootstrapError(
             "%s failed:\n%s (exit code = %d)" %
             (PSQL, e.output, e.returncode)
@@ -167,16 +168,16 @@
     ]
     try:
         if verbose:
-            print "Executing: %s" % (" ".join(cmdArgs))
+            print("Executing: %s" % (" ".join(cmdArgs)))
         out = subprocess.check_output(cmdArgs, stderr=subprocess.STDOUT)
         if verbose:
-            print out
+            print(out)
         if "already exists" in out:
             return False
         return True
     except subprocess.CalledProcessError, e:
         if verbose:
-            print e.output
+            print(e.output)
         raise BootstrapError(
             "%s failed:\n%s (exit code = %d)" %
             (PSQL, e.output, e.returncode)
@@ -216,9 +217,9 @@
     try:
         newlyCreated = createUser(verbose=verbose)
         if newlyCreated:
-            print "Database user '%s' created" % (USERNAME,)
+            print("Database user '%s' created" % (USERNAME,))
         else:
-            print "Database User '%s' exists" % (USERNAME,)
+            print("Database User '%s' exists" % (USERNAME,))
     except BootstrapError, e:
         error("Failed to create database user '%s': %s" % (USERNAME, e))
 
@@ -226,9 +227,9 @@
     try:
         newlyCreated = createDatabase(verbose=verbose)
         if newlyCreated:
-            print "Database '%s' created" % (DATABASENAME,)
+            print("Database '%s' created" % (DATABASENAME,))
         else:
-            print "Database '%s' exists" % (DATABASENAME,)
+            print("Database '%s' exists" % (DATABASENAME,))
     except BootstrapError, e:
         error("Failed to create database '%s': %s" % (DATABASENAME, e))
 
@@ -242,20 +243,20 @@
     try:
         data = open(SCHEMAFILE).read()
     except IOError:
-        print "Unable to open the schema file: %s" % (SCHEMAFILE,)
+        print("Unable to open the schema file: %s" % (SCHEMAFILE,))
     else:
         found = re.search("insert into CALENDARSERVER values \('VERSION', '(\d+)'\);", data)
         if found is None:
-            print "Schema is missing required schema VERSION insert statement: %s" % (SCHEMAFILE,)
+            print("Schema is missing required schema VERSION insert statement: %s" % (SCHEMAFILE,))
         else:
             required_version = int(found.group(1))
             if version == required_version:
-                print "Latest schema version (%d) is installed" % (version,)
+                print("Latest schema version (%d) is installed" % (version,))
         
             elif version == 0: # No schema installed
                 installSchema(verbose=verbose)
                 version = getSchemaVersion(verbose=verbose)
-                print "Successfully installed schema version %d" % (version,)
+                print("Successfully installed schema version %d" % (version,))
         
             else: # upgrade needed
                 error(

Modified: CalendarServer/trunk/calendarserver/tools/calverify.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/calverify.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/calverify.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+
 from twistedcaldav.directory.directory import DirectoryService
 from twistedcaldav.datafilters.peruserdata import PerUserDataFilter
 
@@ -197,8 +199,8 @@
 
 def printusage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         CalVerifyOptions().opt_help()
     except SystemExit:
@@ -741,7 +743,7 @@
 
             returnValue(True)
         except Exception, e:
-            print "Failed to remove resource whilst fixing: %d\n%s" % (resid, e,)
+            print("Failed to remove resource whilst fixing: %d\n%s" % (resid, e,))
             returnValue(False)
 
 
@@ -1024,7 +1026,7 @@
                 result = False
                 message = "Exception for validCalendarData"
                 if self.options["verbose"]:
-                    print e
+                    print(e)
             if not result:
                 results_bad.append((owner, uid, resid, message))
                 badlen += 1
@@ -1258,8 +1260,8 @@
                 self.txn._migrating = True
                 component = yield calendarObj.setComponent(component)
             except Exception, e:
-                print e, component
-                print traceback.print_exc()
+                print(e, component)
+                print(traceback.print_exc())
                 result = False
                 message = "Exception fix: "
             yield self.txn.commit()
@@ -1520,7 +1522,7 @@
                         eachAttendeesOwnStatus[organizerAttendee] = self.buildAttendeeStates(calendar, self.start, self.end, attendee_only=organizerAttendee)
                         attendeeResIDs[(organizerAttendee, uid)] = attresid
                         attendeeCreatedModified[organizerAttendee] = (att_created, att_modified,)
-                        #print "Reloaded missing attendee data"
+                        #print("Reloaded missing attendee data")
 
                 # If an entry for the attendee exists, then check whether attendee status matches
                 if organizerAttendee in eachAttendeesOwnStatus:
@@ -1679,7 +1681,7 @@
                 self.buildResourceInfo(rows, onlyOrganizer=True)
 
                 #if uid in self.organized_byuid:
-                #    print "Reloaded missing organizer data: %s" % (uid,)
+                #    print("Reloaded missing organizer data: %s" % (uid,))
 
             if uid not in self.organized_byuid:
 
@@ -1864,7 +1866,7 @@
             returnValue(True)
 
         except Exception, e:
-            print "Failed to fix resource: %d for attendee: %s\n%s" % (orgresid, attendee, e,)
+            print("Failed to fix resource: %d for attendee: %s\n%s" % (orgresid, attendee, e,))
             returnValue(False)
 
 

Modified: CalendarServer/trunk/calendarserver/tools/calverify_diff.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/calverify_diff.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/calverify_diff.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import getopt
 import sys
@@ -77,16 +78,16 @@
 
 def diff(results1, results2):
     
-    print "\n\nEvents missing from Attendee's calendars"
+    print("\n\nEvents missing from Attendee's calendars")
     diffSets(results1["table1"], results2["table1"])
     
-    print "\n\nEvents mismatched between Organizer's and Attendee's calendars"
+    print("\n\nEvents mismatched between Organizer's and Attendee's calendars")
     diffSets(results1["table2"], results2["table2"])
     
-    print "\n\nAttendee events missing in Organizer's calendar"
+    print("\n\nAttendee events missing in Organizer's calendar")
     diffSets(results1["table3"], results2["table3"])
     
-    print "\n\nAttendee events mismatched in Organizer's calendar"
+    print("\n\nAttendee events mismatched in Organizer's calendar")
     diffSets(results1["table4"], results2["table4"])
 
 def diffSets(results1, results2):
@@ -95,20 +96,20 @@
     s2 = set(results2)
     
     d = s1 - s2
-    print "\nIn first, not in second: (%d)" % (len(d),)
+    print("\nIn first, not in second: (%d)" % (len(d),))
     for i in sorted(d):
-        print i
+        print(i)
     
     d = s2 - s1
-    print "\nIn second, not in first: (%d)" % (len(d),)
+    print("\nIn second, not in first: (%d)" % (len(d),))
     for i in sorted(d):
-        print i
+        print(i)
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: calverify_diff [options] FILE1 FILE2
+    print("""Usage: calverify_diff [options] FILE1 FILE2
 Options:
     -h          Print this help and exit
 
@@ -119,7 +120,7 @@
 Description:
     This utility will analyze the output of two calverify runs
     and show what is different between the two.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -143,10 +144,10 @@
         fname1 = args[0]
         fname2 = args[1]
 
-    print "*** CalVerify diff from %s to %s" % (
+    print("*** CalVerify diff from %s to %s" % (
         os.path.basename(fname1),
         os.path.basename(fname2),
-    )
+    ))
     results1 = analyze(fname1)
     results2 = analyze(fname2)
     diff(results1, results2)

Modified: CalendarServer/trunk/calendarserver/tools/changeip_calendar.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/changeip_calendar.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/changeip_calendar.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -9,7 +9,7 @@
 # Software License Agreement accompanying the package this file is a
 # part of.  You may not port this file to another platform without
 # Apple's written consent.
-
+from __future__ import print_function
 from __future__ import with_statement
 
 import os
@@ -21,15 +21,15 @@
 
 def usage():
     name = os.path.basename(sys.argv[0])
-    print "Usage: %s [-hv] old-ip new-ip [old-hostname new-hostname]" % (name,)
-    print "  Options:"
-    print "    -h           - print this message and exit"
-    print "    -v           - print additional information when running"
-    print "  Arguments:"
-    print "    old-ip       - current IPv4 address of the server"
-    print "    new-ip       - new IPv4 address of the server"
-    print "    old-hostname - current FQDN for the server"
-    print "    new-hostname - new FQDN for the server"
+    print("Usage: %s [-hv] old-ip new-ip [old-hostname new-hostname]" % (name,))
+    print("  Options:")
+    print("    -h           - print this message and exit")
+    print("    -v           - print additional information when running")
+    print("  Arguments:")
+    print("    old-ip       - current IPv4 address of the server")
+    print("    new-ip       - new IPv4 address of the server")
+    print("    old-hostname - current FQDN for the server")
+    print("    new-hostname - new FQDN for the server")
 
 
 def main():
@@ -38,7 +38,7 @@
 
     # Since the serveradmin command must be run as root, so must this script
     if os.getuid() != 0:
-        print "%s must be run as root" % (name,)
+        print("%s must be run as root" % (name,))
         sys.exit(1)
 
     try:
@@ -74,15 +74,15 @@
         oldHostname = newHostname = None
 
     if verbose:
-        print "Calendar Server: updating %s" % (configFile,)
+        print("Calendar Server: updating %s" % (configFile,))
 
     try:
         plist = readPlist(configFile)
     except IOError:
-        print "Error: could not open %s" % (configFile,)
+        print("Error: could not open %s" % (configFile,))
         sys.exit(1)
     except Exception, e:
-        print "Error: could not parse %s" % (configFile,)
+        print("Error: could not parse %s" % (configFile,))
         raise e
 
     writePlist(plist, "%s.changeip.bak" % (configFile,))
@@ -91,7 +91,7 @@
     writePlist(plist, configFile)
 
     if verbose:
-        print "Calendar Server: done"
+        print("Calendar Server: done")
 
 def updatePlist(plist, oldIP, newIP, oldHostname, newHostname, verbose=False):
 
@@ -109,7 +109,7 @@
         if oldHostname and newHostname:
             newValue = newValue.replace(oldHostname, newHostname)
         if verbose and value != newValue:
-            print "Changed %s -> %s" % (value, newValue)
+            print("Changed %s -> %s" % (value, newValue))
         return newValue
 
     for keyPath in keys:

Modified: CalendarServer/trunk/calendarserver/tools/config.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/config.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/config.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool reads the Calendar Server configuration file and emits the
@@ -31,16 +32,16 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] config_key" % (name,)
-    print ""
-    print "Print the value of the given config key."
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config: Specify caldavd.plist configuration path"
+    print("usage: %s [options] config_key" % (name,))
+    print("")
+    print("Print the value of the given config key.")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config: Specify caldavd.plist configuration path")
 
     if e:
         sys.exit(64)

Modified: CalendarServer/trunk/calendarserver/tools/dbinspect.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/dbinspect.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/dbinspect.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool allows data in the database to be directly inspected using a set
@@ -49,8 +50,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         DBInspectOptions().opt_help()
     except SystemExit:
@@ -152,8 +153,8 @@
                 count,
             ))
 
-        print "\n"
-        print "Database Tables (total=%d):\n" % (len(results),)
+        print("\n")
+        print("Database Tables (total=%d):\n" % (len(results),))
         table.printTable()
 
 
@@ -189,8 +190,8 @@
                 shortname,
             ))
 
-        print "\n"
-        print "Calendar Homes (total=%d, missing=%d):\n" % (len(uids), missing,)
+        print("\n")
+        print("Calendar Homes (total=%d, missing=%d):\n" % (len(uids), missing,))
         table.printTable()
 
 
@@ -245,8 +246,8 @@
             "%.2f" % ((1.0 * totals[2]) / totals[0] if totals[0] else 0,),
         ))
 
-        print "\n"
-        print "Calendars with resource count (total=%d):\n" % (len(results),)
+        print("\n")
+        print("Calendars with resource count (total=%d):\n" % (len(results),))
         table.printTable()
 
 
@@ -292,8 +293,8 @@
                 count
             ))
 
-        print "\n"
-        print "Calendars with resource count (total=%d):\n" % (len(uids),)
+        print("\n")
+        print("Calendars with resource count (total=%d):\n" % (len(uids),))
         table.printTable()
 
 
@@ -346,8 +347,8 @@
             totals[1] += count
         table.addFooter(("Total", "", totals[0], "", totals[1]))
 
-        print "\n"
-        print "Calendars with resource count (total=%d):\n" % (len(uids),)
+        print("\n")
+        print("Calendars with resource count (total=%d):\n" % (len(uids),))
         table.printTable()
 
 
@@ -397,8 +398,8 @@
                 caluid
             ))
 
-        print "\n"
-        print "Calendar events (total=%d):\n" % (len(uids),)
+        print("\n")
+        print("Calendar events (total=%d):\n" % (len(uids),))
         table.printTable()
 
 
@@ -435,7 +436,7 @@
         try:
             int(rid)
         except ValueError:
-            print 'Resource ID must be an integer'
+            print('Resource ID must be an integer')
             returnValue(None)
         uids = yield self.getEvents(txn, rid)
 
@@ -450,8 +451,8 @@
                 rid,
             ))
 
-        print "\n"
-        print "Calendar events (total=%d):\n" % (len(uids),)
+        print("\n")
+        print("Calendar events (total=%d):\n" % (len(uids),))
         table.printTable()
 
 
@@ -492,9 +493,9 @@
         table.addRow(("Resource ID:", resource_id))
         table.addRow(("Created", created))
         table.addRow(("Modified", modified))
-        print "\n"
+        print("\n")
         table.printTable()
-        print data
+        print(data)
 
 
     @inlineCallbacks
@@ -533,13 +534,13 @@
         try:
             int(rid)
         except ValueError:
-            print 'Resource ID must be an integer'
+            print('Resource ID must be an integer')
             returnValue(None)
         result = yield self.getData(txn, rid)
         if result:
             self.printEventDetails(txn, result[0])
         else:
-            print "Could not find resource"
+            print("Could not find resource")
 
 
     def getData(self, txn, rid):
@@ -561,7 +562,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, uid):
@@ -583,7 +584,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, name):
@@ -606,7 +607,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, uid):
@@ -630,7 +631,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, uid, name):
@@ -650,7 +651,7 @@
         path = raw_input("Path: ")
         pathbits = path.split("/")
         if len(pathbits) != 6:
-            print "Not a valid calendar object resource path"
+            print("Not a valid calendar object resource path")
             returnValue(None)
         homeName = pathbits[3]
         calendarName = pathbits[4]
@@ -660,7 +661,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, homeName, calendarName, resourceName):
@@ -692,7 +693,7 @@
             for result in rows:
                 self.printEventDetails(txn, result)
         else:
-            print "Could not find icalendar data"
+            print("Could not find icalendar data")
 
 
     def getData(self, txn, text):
@@ -719,18 +720,18 @@
         try:
             start = PyCalendarDateTime.parseText(start)
         except ValueError:
-            print "Invalid start value"
+            print("Invalid start value")
             returnValue(None)
         try:
             end = PyCalendarDateTime.parseText(end)
         except ValueError:
-            print "Invalid end value"
+            print("Invalid end value")
             returnValue(None)
         timerange = caldavxml.TimeRange(start=start.getText(), end=end.getText())
 
         home = yield txn.calendarHomeWithUID(uid)
         if home is None:
-            print "Could not find calendar home"
+            print("Could not find calendar home")
             returnValue(None)
 
         yield self.eventsForEachCalendar(home, uid, timerange)
@@ -777,9 +778,9 @@
             table.addRow(("Resource ID:", event._resourceID))
             table.addRow(("Created", event.created()))
             table.addRow(("Modified", event.modified()))
-            print "\n"
+            print("\n")
             table.printTable()
-            print ical_data.getTextWithTimezones(includeTimezones=False)
+            print(ical_data.getTextWithTimezones(includeTimezones=False))
 
 
 
@@ -791,7 +792,7 @@
     def doIt(self, txn):
 
         if raw_input("Do you really want to remove all data [y/n]: ")[0].lower() != 'y':
-            print "No data removed"
+            print("No data removed")
             returnValue(None)
 
         wipeout = (
@@ -829,21 +830,21 @@
 
         for tableschema in wipeout:
             yield self.removeTableData(txn, tableschema)
-            print "Removed rows in table %s" % (tableschema,)
+            print("Removed rows in table %s" % (tableschema,))
 
         if calendaruserproxy.ProxyDBService is not None:
             calendaruserproxy.ProxyDBService.clean() #@UndefinedVariable
-            print "Removed all proxies"
+            print("Removed all proxies")
         else:
-            print "No proxy database to clean."
+            print("No proxy database to clean.")
 
         fp = FilePath(config.AttachmentsRoot)
         if fp.exists():
             for child in fp.children():
                 child.remove()
-            print "Removed attachments."
+            print("Removed attachments.")
         else:
-            print "No attachments path to delete."
+            print("No attachments path to delete.")
 
 
     @inlineCallbacks
@@ -906,7 +907,7 @@
         try:
             yield self.runCommandByName(self.commands[position])
         except IndexError:
-            print "Position %d not available" % (position,)
+            print("Position %d not available" % (position,))
             returnValue(None)
 
 
@@ -915,7 +916,7 @@
         try:
             yield self.runCommand(self.commandMap[name])
         except IndexError:
-            print "Unknown command: '%s'" % (name,)
+            print("Unknown command: '%s'" % (name,))
 
 
     @inlineCallbacks
@@ -927,18 +928,18 @@
             yield txn.commit()
         except Exception, e:
             traceback.print_exc()
-            print "Command '%s' failed because of: %s" % (cmd.name(), e,)
+            print("Command '%s' failed because of: %s" % (cmd.name(), e,))
             yield txn.abort()
 
 
     def printCommands(self):
 
-        print "\n<---- Commands ---->"
+        print("\n<---- Commands ---->")
         for ctr, name in enumerate(self.commands):
-            print "%d. %s" % (ctr + 1, name,)
+            print("%d. %s" % (ctr + 1, name,))
         if self.options["purging"]:
-            print "P. Purge\n"
-        print "Q. Quit\n"
+            print("P. Purge\n")
+        print("Q. Quit\n")
 
 
     @inlineCallbacks
@@ -958,7 +959,7 @@
                 try:
                     position = int(cmd)
                 except ValueError:
-                    print "Invalid command. Try again.\n"
+                    print("Invalid command. Try again.\n")
                     continue
 
                 yield self.runCommandByPosition(position - 1)
@@ -977,7 +978,7 @@
             try:
                 calendaruserproxy.ProxyDBService = proxydbClass(**config.ProxyDBService.params)
             except IOError:
-                print "Could not start proxydb service"
+                print("Could not start proxydb service")
         return self._directory
 
 

Modified: CalendarServer/trunk/calendarserver/tools/dkimtool.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/dkimtool.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/dkimtool.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -41,7 +41,7 @@
     if options["key"]:
         open(options["key"], "w").write(output)
     else:
-        print output
+        print(output)
         lineBreak = True
 
     output = key.publickey().exportKey()
@@ -50,7 +50,7 @@
     else:
         if lineBreak:
             print
-        print output
+        print(output)
         lineBreak = True
 
     if options["txt"]:
@@ -58,7 +58,7 @@
         txt = "v=DKIM1; p=%s" % (output,)
         if lineBreak:
             print
-        print txt
+        print(txt)
 
 
 
@@ -105,7 +105,7 @@
 
     s = StringIO()
     _writeRequest(dkim, s)
-    print s.getvalue()
+    print(s.getvalue())
 
 
 
@@ -131,9 +131,9 @@
     try:
         yield dkim.verify()
     except DKIMVerificationError, e:
-        print "Verification Failed: %s" % (e,)
+        print("Verification Failed: %s" % (e,))
     else:
-        print "Verification Succeeded"
+        print("Verification Succeeded")
 
 
 
@@ -192,8 +192,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         DKIMToolOptions().opt_help()
     except SystemExit:
@@ -282,7 +282,7 @@
     try:
         yield fn(options)
     except Exception, e:
-        print e
+        print(e)
     finally:
         reactor.stop()
 

Modified: CalendarServer/trunk/calendarserver/tools/doublequotefix.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/doublequotefix.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/doublequotefix.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import datetime
 import getopt
@@ -32,21 +33,21 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options]" % (name,)
-    print ""
-    print "Fix double-quote/escape bugs in iCalendar data."
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -p <path>: path to calendar server document root [icalserver default]"
-    print "  -u <path>: path to file containing uris to process [uris.txt]"
-    print "  --fix: Apply fixes, otherwise only check for problems"
-    print ""
-    print "uris: list of uris to process"
+    print("usage: %s [options]" % (name,))
+    print("")
+    print("Fix double-quote/escape bugs in iCalendar data.")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -p <path>: path to calendar server document root [icalserver default]")
+    print("  -u <path>: path to file containing uris to process [uris.txt]")
+    print("  --fix: Apply fixes, otherwise only check for problems")
+    print("")
+    print("uris: list of uris to process")
 
     if e:
         sys.exit(64)
@@ -76,7 +77,7 @@
     # Verify we have a valid path
     pathBits = uri.strip("/").rstrip("/").split("/")
     if len(pathBits) != 4 or pathBits[0] != "calendars" or pathBits[1] != "__uids__":
-        print "Invalid uri (ignoring): %s" % (uri,)
+        print("Invalid uri (ignoring): %s" % (uri,))
         totalErrors += 1
         return
 
@@ -92,7 +93,7 @@
     )
     
     if not os.path.exists(calendarPath):
-        print "Calendar path does not exist: %s" % (calendarPath,)
+        print("Calendar path does not exist: %s" % (calendarPath,))
         totalErrors += 1
         return
 
@@ -109,7 +110,7 @@
             f = open(icsPath)
             icsData = f.read()
         except Exception, e:
-            print "Failed to read file %s due to %s" % (icsPath, str(e),)
+            print("Failed to read file %s due to %s" % (icsPath, str(e),))
             totalErrors += 1
             continue
         finally:
@@ -131,7 +132,7 @@
                     f = open(icsPath, "w")
                     f.write(icsData)
                 except Exception, e:
-                    print "Failed to write file %s due to %s" % (icsPath, str(e),)
+                    print("Failed to write file %s due to %s" % (icsPath, str(e),))
                     totalErrors += 1
                     continue
                 finally:
@@ -140,9 +141,9 @@
                 # Change ETag on written resource
                 updateEtag(icsPath, icsData)
                 didFix = True
-                print "Problem fixed in: <BasePath>%s" % (icsPath[basePathLength:],)
+                print("Problem fixed in: <BasePath>%s" % (icsPath[basePathLength:],))
             else:
-                print "Problem found in: <BasePath>%s" % (icsPath[basePathLength:],)
+                print("Problem found in: <BasePath>%s" % (icsPath[basePathLength:],))
             totalProblems += 1
      
     # Change CTag on calendar collection if any resource was written
@@ -182,24 +183,24 @@
     for line in f:
         pos = line.find("/calendars/")
         if pos == -1:
-            print "Ignored log line: %s" % (line,)
+            print("Ignored log line: %s" % (line,))
             continue
         uris.add(line[pos:].split()[0])
     uris = list(uris)
     uris.sort()
     f.close()
 
-    print "Base Path is: %s" % (basePath,)
-    print "Number of unique URIs to fix: %d" % (len(uris),)
-    print ""
+    print("Base Path is: %s" % (basePath,))
+    print("Number of unique URIs to fix: %d" % (len(uris),))
+    print("")
     for uri in uris:
         scanURI(uri, basePath, doFix)
 
-    print ""
-    print "---------------------"
-    print "Total Problems %s: %d of %d" % ("Fixed" if doFix else "Found", totalProblems, totalScanned,)
+    print("")
+    print("---------------------")
+    print("Total Problems %s: %d of %d" % ("Fixed" if doFix else "Found", totalProblems, totalScanned,))
     if totalErrors:
-        print "Total Errors: %s" % (totalErrors,)
+        print("Total Errors: %s" % (totalErrors,))
 
 if __name__ == '__main__':
     

Modified: CalendarServer/trunk/calendarserver/tools/export.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/export.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/export.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool reads calendar data from a series of inputs and generates a single
@@ -52,8 +53,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         ExportOptions().opt_help()
     except SystemExit:

Modified: CalendarServer/trunk/calendarserver/tools/fixcalendardata.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/fixcalendardata.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/fixcalendardata.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import re
 import datetime
@@ -38,24 +39,24 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options]" % (name,)
-    print ""
-    print "Fix double-quote/escape bugs in iCalendar data."
-    print "Fix incorrect use of TZID in iCalendar data."
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config: Specify caldavd.plist configuration path"
-    print "  -o <path>: path to file for scan results [problems.txt]"
-    print "  -v: print each calendar home scanned"
-    print "  --scan: Scan for problems"
-    print "  --fix: Apply fixes"
-    print ""
-    print "One of --scan or --fix must be specified. Both may be specified"
+    print("usage: %s [options]" % (name,))
+    print("")
+    print("Fix double-quote/escape bugs in iCalendar data.")
+    print("Fix incorrect use of TZID in iCalendar data.")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config: Specify caldavd.plist configuration path")
+    print("  -o <path>: path to file for scan results [problems.txt]")
+    print("  -v: print each calendar home scanned")
+    print("  --scan: Scan for problems")
+    print("  --fix: Apply fixes")
+    print("")
+    print("One of --scan or --fix must be specified. Both may be specified")
 
     if e:
         sys.exit(64)
@@ -101,7 +102,7 @@
 
 def scanCalendarHome(basePath, calendarHome, scanFile, doFix):
     if verbose:
-        print "Scanning: %s" % (calendarHome,)
+        print("Scanning: %s" % (calendarHome,))
     
     for item in os.listdir(calendarHome):
         calendarPath = os.path.join(calendarHome, item)
@@ -116,7 +117,7 @@
     global totalScanned
 
     if not os.path.exists(calendarPath):
-        print "Calendar path does not exist: %s" % (calendarPath,)
+        print("Calendar path does not exist: %s" % (calendarPath,))
         totalErrors += 1
         return
 
@@ -134,7 +135,7 @@
             f = open(icsPath)
             icsData = f.read()
         except Exception, e:
-            print "Failed to read file %s due to %s" % (icsPath, str(e),)
+            print("Failed to read file %s due to %s" % (icsPath, str(e),))
             totalErrors += 1
             continue
         finally:
@@ -158,9 +159,9 @@
             if doFix:
                 if fixPath(icsPath, icsData, fixQuotes, fixTZIDs, fixMultiVALARMs):
                     didFix = True
-                    print "Problems %s fixed in: <BasePath>%s" % (",".join(problems), icsPath[basePathLength:],)
+                    print("Problems %s fixed in: <BasePath>%s" % (",".join(problems), icsPath[basePathLength:],))
             else:
-                print "Problem %s found in: <BasePath>%s" % (",".join(problems), icsPath[basePathLength:],)
+                print("Problem %s found in: <BasePath>%s" % (",".join(problems), icsPath[basePathLength:],))
                 scanFile.write(icsPath + "\n")
             totalProblems += 1
      
@@ -220,7 +221,7 @@
         f = open(scanPath)
         lines = [line[:-1] for line in f]
     except Exception, e:
-        print "Failed to read file %s due to %s" % (scanPath, str(e),)
+        print("Failed to read file %s due to %s" % (scanPath, str(e),))
         totalErrors += 1
         return
     finally:
@@ -241,7 +242,7 @@
             icsPath = os.path.join(calendarPath, icsName)
             if fixPath(icsPath):
                 didFix = True
-                print "Problem fixed in: <BasePath>%s" % (icsPath[basePathLength:],)
+                print("Problem fixed in: <BasePath>%s" % (icsPath[basePathLength:],))
                 totalProblems += 1
          
         # Change CTag on calendar collection if any resource was written
@@ -260,7 +261,7 @@
             f = open(icsPath)
             icsData = f.read()
         except Exception, e:
-            print "Failed to read file %s due to %s" % (icsPath, str(e),)
+            print("Failed to read file %s due to %s" % (icsPath, str(e),))
             totalErrors += 1
             return False
         finally:
@@ -302,7 +303,7 @@
         f = open(icsPath, "w")
         f.write(icsData)
     except Exception, e:
-        print "Failed to write file %s due to %s" % (icsPath, str(e),)
+        print("Failed to write file %s due to %s" % (icsPath, str(e),))
         totalErrors += 1
         return False
     finally:
@@ -348,29 +349,29 @@
     basePath = parsePlist(plistPath)
 
     start = time.time()
-    print "Base Path is: %s" % (basePath,)
+    print("Base Path is: %s" % (basePath,))
     if doScan:
         if doFix:
-            print "Scanning data store and fixing"
+            print("Scanning data store and fixing")
             scanFile = None
         else:
-            print "Scanning data store and writing results to '%s'" % (scanPath,)
+            print("Scanning data store and writing results to '%s'" % (scanPath,))
             try:
                 scanFile = open(scanPath, "w")
             except Exception, e:
-                print "Failed to open file for writing %s due to %s" % (scanPath, str(e),)
+                print("Failed to open file for writing %s due to %s" % (scanPath, str(e),))
         scanData(basePath, scanFile, doFix)
     elif doFix:
-        print "Fixing data using results from '%s'" % (scanPath,)
+        print("Fixing data using results from '%s'" % (scanPath,))
         fixData(basePath, scanPath)
     difftime = time.time() - start
 
-    print ""
-    print "---------------------"
-    print "Total Problems %s: %d of %d" % ("Fixed" if doFix else "Found", totalProblems, totalScanned,)
+    print("")
+    print("---------------------")
+    print("Total Problems %s: %d of %d" % ("Fixed" if doFix else "Found", totalProblems, totalScanned,))
     if totalErrors:
-        print "Total Errors: %s" % (totalErrors,)
-    print "Time taken (secs): %.1f" % (difftime,)
+        print("Total Errors: %s" % (totalErrors,))
+    print("Time taken (secs): %.1f" % (difftime,))
 
 if __name__ == '__main__':
     

Modified: CalendarServer/trunk/calendarserver/tools/gateway.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/gateway.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/gateway.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from getopt import getopt, GetoptError
 import os
@@ -40,15 +41,15 @@
 def usage(e=None):
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options]" % (name,)
-    print ""
-    print "  TODO: describe usage"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -e --error: send stderr to stdout"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print ""
+    print("usage: %s [options]" % (name,))
+    print("")
+    print("  TODO: describe usage")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -e --error: send stderr to stdout")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("")
 
     if e:
         sys.exit(64)

Modified: CalendarServer/trunk/calendarserver/tools/icalsplit.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/icalsplit.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/icalsplit.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 import sys
@@ -53,7 +54,7 @@
         uid = subcalendar.resourceUID()
         subFileName = os.path.join(outputDirectory, uid + ".ics")
 
-        print "Writing %s" % (subFileName,)
+        print("Writing %s" % (subFileName,))
 
         subcalendar_file = file(subFileName, "w")
         try:
@@ -64,19 +65,19 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] input_file output_directory" % (name,)
-    print ""
-    print "  Splits up monolithic iCalendar data into separate files for each"
-    print "  subcomponent so as to comply with CalDAV requirements for"
-    print "  individual resources."
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print ""
+    print("usage: %s [options] input_file output_directory" % (name,))
+    print("")
+    print("  Splits up monolithic iCalendar data into separate files for each")
+    print("  subcomponent so as to comply with CalDAV requirements for")
+    print("  individual resources.")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("")
 
     if e:
         sys.exit(64)

Modified: CalendarServer/trunk/calendarserver/tools/loadaugmentdb.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/loadaugmentdb.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/loadaugmentdb.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.tools.managetimezones import StandardIOObserver
 from calendarserver.tools.util import loadConfig, getDirectory, \
@@ -43,20 +44,20 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options]" % (name,)
-    print ""
-    print "Populate an sqlite or PostgreSQL augments database with values"
-    print "from an XML augments file."
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config: Specify caldavd.plist configuration path"
-    print "  -x --xmlfile: Specify xml augments file path"
-    print "  -r --remove: Remove all entries from the database"
+    print("usage: %s [options]" % (name,))
+    print("")
+    print("Populate an sqlite or PostgreSQL augments database with values")
+    print("from an XML augments file.")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config: Specify caldavd.plist configuration path")
+    print("  -x --xmlfile: Specify xml augments file path")
+    print("  -r --remove: Remove all entries from the database")
 
     if e:
         sys.exit(64)
@@ -160,10 +161,10 @@
             yield augment.AugmentService.removeAugmentRecords(remove_uids)
             removed = len(remove_uids)
 
-        print "Changes:"
-        print "  Added: %d" % (added,)
-        print "  Changed: %d" % (updated,)
-        print "  Removed: %d" % (removed,)
+        print("Changes:")
+        print("  Added: %d" % (added,))
+        print("  Changed: %d" % (updated,))
+        print("  Removed: %d" % (removed,))
     finally:
         #
         # Stop the reactor

Modified: CalendarServer/trunk/calendarserver/tools/managepostgres.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/managepostgres.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/managepostgres.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from optparse import OptionParser
 import os
@@ -22,11 +23,11 @@
 import time
 
 def error(s):
-    print s
+    print(s)
     sys.exit(1)
 
 def cmd(s):
-    print s
+    print(s)
     subprocess.call(s, shell=True)
 
 def doInit(basedir):

Modified: CalendarServer/trunk/calendarserver/tools/managetimezones.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/managetimezones.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/managetimezones.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from pycalendar.calendar import PyCalendar
 from pycalendar.datetime import PyCalendarDateTime
@@ -65,20 +66,20 @@
     Refresh data from IANA.
     """
 
-    print "Downloading latest data from IANA"
+    print("Downloading latest data from IANA")
     if tzvers:
         path = "http://www.iana.org/time-zones/repository/releases/tzdata%s.tar.gz" % (tzvers,)
     else:
         path = "http://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
         tzvers = "Latest (%s)" % (PyCalendarDateTime.getToday().getText(),)
     data = urllib.urlretrieve(path)
-    print "Extract data at: %s" % (data[0])
+    print("Extract data at: %s" % (data[0]))
     rootdir = tempfile.mkdtemp()
     zonedir = os.path.join(rootdir, "tzdata")
     os.mkdir(zonedir)
     with tarfile.open(data[0], "r:gz") as t:
         t.extractall(zonedir)
-    print "Converting data at: %s" % (zonedir,)
+    print("Converting data at: %s" % (zonedir,))
     startYear = 1800
     endYear = PyCalendarDateTime.getToday().getYear() + 10
     PyCalendar.sProdID = "-//calendarserver.org//Zonal//EN"
@@ -88,22 +89,22 @@
         parser.parse(os.path.join(zonedir, file))
 
     parser.generateZoneinfoFiles(os.path.join(rootdir, "zoneinfo"), startYear, endYear, filterzones=())
-    print "Copy new zoneinfo to destination: %s" % (tzpath,)
+    print("Copy new zoneinfo to destination: %s" % (tzpath,))
     z = FilePath(os.path.join(rootdir, "zoneinfo"))
     tz = FilePath(tzpath)
     z.copyTo(tz)
-    print "Updating XML file at: %s" % (xmlfile,)
+    print("Updating XML file at: %s" % (xmlfile,))
     tzdb.readDatabase()
     tzdb.updateDatabase()
-    print "Current total: %d" % (len(tzdb.timezones),)
-    print "Total Changed: %d" % (tzdb.changeCount,)
+    print("Current total: %d" % (len(tzdb.timezones),))
+    print("Total Changed: %d" % (tzdb.changeCount,))
     if tzdb.changeCount:
-        print "Changed:"
+        print("Changed:")
         for k in sorted(tzdb.changed):
-            print "  %s" % (k,)
+            print("  %s" % (k,))
 
     versfile = os.path.join(os.path.dirname(xmlfile), "version.txt")
-    print "Updating version file at: %s" % (versfile,)
+    print("Updating version file at: %s" % (versfile,))
     with open(versfile, "w") as f:
         f.write("Olson data source: %s\n" % (tzvers,))
 
@@ -114,9 +115,9 @@
     Create new xml file.
     """
 
-    print "Creating new XML file at: %s" % (xmlfile,)
+    print("Creating new XML file at: %s" % (xmlfile,))
     tzdb.createNewDatabase()
-    print "Current total: %d" % (len(tzdb.timezones),)
+    print("Current total: %d" % (len(tzdb.timezones),))
 
 
 
@@ -125,15 +126,15 @@
     Update xml file.
     """
 
-    print "Updating XML file at: %s" % (xmlfile,)
+    print("Updating XML file at: %s" % (xmlfile,))
     tzdb.readDatabase()
     tzdb.updateDatabase()
-    print "Current total: %d" % (len(tzdb.timezones),)
-    print "Total Changed: %d" % (tzdb.changeCount,)
+    print("Current total: %d" % (len(tzdb.timezones),))
+    print("Total Changed: %d" % (tzdb.changeCount,))
     if tzdb.changeCount:
-        print "Changed:"
+        print("Changed:")
         for k in sorted(tzdb.changed):
-            print "  %s" % (k,)
+            print("  %s" % (k,))
 
 
 
@@ -142,12 +143,12 @@
     List current timezones from xml file.
     """
 
-    print "Listing XML file at: %s" % (xmlfile,)
+    print("Listing XML file at: %s" % (xmlfile,))
     tzdb.readDatabase()
-    print "Current timestamp: %s" % (tzdb.dtstamp,)
-    print "Timezones:"
+    print("Current timestamp: %s" % (tzdb.dtstamp,))
+    print("Timezones:")
     for k in sorted(tzdb.timezones.keys()):
-        print "  %s" % (k,)
+        print("  %s" % (k,))
 
 
 
@@ -156,16 +157,16 @@
     Check for local timezone changes.
     """
 
-    print "Changes from XML file at: %s" % (xmlfile,)
+    print("Changes from XML file at: %s" % (xmlfile,))
     tzdb.readDatabase()
-    print "Check timestamp: %s" % (changed,)
-    print "Current timestamp: %s" % (tzdb.dtstamp,)
+    print("Check timestamp: %s" % (changed,))
+    print("Current timestamp: %s" % (tzdb.dtstamp,))
     results = [k for k, v in tzdb.timezones.items() if v.dtstamp > changed]
-    print "Total Changed: %d" % (len(results),)
+    print("Total Changed: %d" % (len(results),))
     if results:
-        print "Changed:"
+        print("Changed:")
         for k in sorted(results):
-            print "  %s" % (k,)
+            print("  %s" % (k,))
 
 
 
@@ -174,11 +175,11 @@
 
     try:
         new, changed = yield tzdb.syncWithServer()
-        print "New:           %d" % (new,)
-        print "Changed:       %d" % (changed,)
-        print "Current total: %d" % (len(tzdb.timezones),)
+        print("New:           %d" % (new,))
+        print("Changed:       %d" % (changed,))
+        print("Current total: %d" % (len(tzdb.timezones),))
     except Exception, e:
-        print "Could not sync with server: %s" % (str(e),)
+        print("Could not sync with server: %s" % (str(e),))
     finally:
         reactor.stop()
 
@@ -192,7 +193,7 @@
     except:
         pass
     if action == "cache":
-        print "Caching from secondary server: %s" % (url,)
+        print("Caching from secondary server: %s" % (url,))
 
         observer = StandardIOObserver()
         observer.start()
@@ -205,10 +206,10 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
-        print
+        print(error_msg)
+        print("")
 
-    print """Usage: managetimezones [options]
+    print("""Usage: managetimezones [options]
 Options:
     -h            Print this help and exit
     -f            XML file path
@@ -232,7 +233,7 @@
     This utility will create, update or list an XML timezone database
     summary file, or refresh iCalendar timezone from IANA (Olson).
 
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)

Modified: CalendarServer/trunk/calendarserver/tools/migrate.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/migrate.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/migrate.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool migrates existing calendar data from any previous calendar server
@@ -36,17 +37,17 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options]" % (name,)
-    print ""
-    print "Migrate calendar data to current version"
-    print __doc__
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config: Specify caldavd.plist configuration path"
+    print("usage: %s [options]" % (name,))
+    print("")
+    print("Migrate calendar data to current version")
+    print(__doc__)
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config: Specify caldavd.plist configuration path")
 
     if e:
         sys.exit(64)

Modified: CalendarServer/trunk/calendarserver/tools/migrate_verify.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/migrate_verify.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/migrate_verify.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+
 from txdav.common.datastore.sql_tables import schema, _BIND_MODE_OWN
 from twext.enterprise.dal.syntax import Select, Parameter
 
@@ -38,8 +40,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         MigrateVerifyOptions().opt_help()
     except SystemExit:

Modified: CalendarServer/trunk/calendarserver/tools/notifications.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/notifications.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/notifications.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.tools.util import loadConfig
 from datetime import datetime
@@ -42,26 +43,26 @@
 
 def usage(e=None):
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] username" % (name,)
-    print ""
-    print " Monitor push notification events from calendar server"
-    print ""
-    print "options:"
-    print "  -a --admin <username>: Specify an administrator username"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -h --help: print this help and exit"
-    print "  -H --host <hostname>: calendar server host name"
-    print "  -n --node <pubsub node>: pubsub node to subscribe to *"
-    print "  -p --port <port number>: calendar server port number"
-    print "  -s --ssl: use https (default is http)"
-    print "  -v --verbose: print additional information including XMPP traffic"
-    print ""
-    print " * The --node option is only required for calendar servers that"
-    print "   don't advertise the push-transports DAV property (such as a Snow"
-    print "   Leopard server).  In this case, --host should specify the name"
-    print "   of the XMPP server and --port should specify the port XMPP is"
-    print "   is listening on."
-    print ""
+    print("usage: %s [options] username" % (name,))
+    print("")
+    print(" Monitor push notification events from calendar server")
+    print("")
+    print("options:")
+    print("  -a --admin <username>: Specify an administrator username")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -h --help: print this help and exit")
+    print("  -H --host <hostname>: calendar server host name")
+    print("  -n --node <pubsub node>: pubsub node to subscribe to *")
+    print("  -p --port <port number>: calendar server port number")
+    print("  -s --ssl: use https (default is http)")
+    print("  -v --verbose: print additional information including XMPP traffic")
+    print("")
+    print(" * The --node option is only required for calendar servers that")
+    print("   don't advertise the push-transports DAV property (such as a Snow")
+    print("   Leopard server).  In this case, --host should specify the name")
+    print("   of the XMPP server and --port should specify the port XMPP is")
+    print("   is listening on.")
+    print("")
 
     if e:
         sys.stderr.write("%s\n" % (e,))
@@ -125,7 +126,7 @@
         try:
             loadConfig(configFileName)
         except ConfigurationError, e:
-            print "Error in configuration: %s" % (e,)
+            print("Error in configuration: %s" % (e,))
             sys.exit(1)
 
         useSSL = config.EnableSSL
@@ -168,7 +169,7 @@
         self.verbose = verbose
 
         if self.verbose:
-            print "JID:", self.jid, "Pubsub service:", self.service
+            print("JID:", self.jid, "Pubsub service:", self.service)
 
         self.presenceSeconds = 60
         self.presenceCall = None
@@ -193,7 +194,7 @@
 
     @inlineCallbacks
     def sigint_handler(self, num, frame):
-        print " Shutting down..."
+        print(" Shutting down...")
         yield self.unsubscribeAll()
         reactor.stop()
 
@@ -206,7 +207,7 @@
     def connected(self, xmlStream):
         self.xmlStream = xmlStream
         if self.verbose:
-            print "XMPP connection successful"
+            print("XMPP connection successful")
             xmlStream.rawDataInFn = self.rawDataIn
             xmlStream.rawDataOutFn = self.rawDataOut
         xmlStream.addObserver("/message/event/items",
@@ -218,25 +219,25 @@
             self.presenceCall.cancel()
             self.presenceCall = None
         if self.verbose:
-            print "XMPP disconnected"
+            print("XMPP disconnected")
 
     def initFailed(self, failure):
         self.xmlStream = None
-        print "XMPP connection failure: %s" % (failure,)
+        print("XMPP connection failure: %s" % (failure,))
         reactor.stop()
 
     @inlineCallbacks
     def authenticated(self, xmlStream):
         if self.verbose:
-            print "XMPP authentication successful"
+            print("XMPP authentication successful")
         self.sendPresence()
         for node, (url, name, kind) in self.nodes.iteritems():
             yield self.subscribe(node, name, kind)
 
-        print "Awaiting notifications (hit Control-C to end)"
+        print("Awaiting notifications (hit Control-C to end)")
 
     def authFailed(self, e):
-        print "XMPP authentication failed"
+        print("XMPP authentication failed")
         reactor.stop()
 
     def sendPresence(self):
@@ -254,10 +255,10 @@
                 node = str(node)
                 url, name, kind = self.nodes.get(node, ("Not subscribed", "Unknown", "Unknown"))
                 timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-                print '%s | Notification for "%s" (%s)' % (timestamp, name, kind)
+                print('%s | Notification for "%s" (%s)' % (timestamp, name, kind))
                 if self.verbose:
-                    print " node = %s" % (node,)
-                    print " url = %s" % (url,)
+                    print(" node = %s" % (node,))
+                    print(" url = %s" % (url,))
 
 
     @inlineCallbacks
@@ -267,14 +268,14 @@
         subElement = pubsubElement.addElement("subscribe")
         subElement["node"] = node
         subElement["jid"] = self.jid
-        print 'Subscribing to "%s" (%s)' % (name, kind)
+        print('Subscribing to "%s" (%s)' % (name, kind))
         if self.verbose:
-            print node
+            print(node)
         try:
             yield iq.send(to=self.service)
-            print "OK"
+            print("OK")
         except Exception, e:
-            print "Subscription failure: %s %s" % (node, e)
+            print("Subscription failure: %s %s" % (node, e))
 
     @inlineCallbacks
     def unsubscribe(self, node, name, kind):
@@ -283,14 +284,14 @@
         subElement = pubsubElement.addElement("unsubscribe")
         subElement["node"] = node
         subElement["jid"] = self.jid
-        print 'Unsubscribing from "%s" (%s)' % (name, kind)
+        print('Unsubscribing from "%s" (%s)' % (name, kind))
         if self.verbose:
-            print node
+            print(node)
         try:
             yield iq.send(to=self.service)
-            print "OK"
+            print("OK")
         except Exception, e:
-            print "Unsubscription failure: %s %s" % (node, e)
+            print("Unsubscription failure: %s %s" % (node, e))
 
 
     @inlineCallbacks
@@ -299,18 +300,18 @@
         iq = IQ(self.xmlStream)
         pubsubElement = iq.addElement("pubsub", defaultUri=self.pubsubNS)
         pubsubElement.addElement("subscriptions")
-        print "Requesting list of subscriptions"
+        print("Requesting list of subscriptions")
         try:
             yield iq.send(to=self.service)
         except Exception, e:
-            print "Subscription list failure: %s" % (e,)
+            print("Subscription list failure: %s" % (e,))
 
 
     def rawDataIn(self, buf):
-        print "RECV: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')
+        print("RECV: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace'))
 
     def rawDataOut(self, buf):
-        print "SEND: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')
+        print("SEND: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace'))
 
 
 class PropfindRequestor(AuthorizedHTTPGetter):
@@ -345,14 +346,14 @@
                 principal = "/principals/users/%s/" % (self.username,)
                 name, homes = (yield self.getPrincipalDetails(principal))
                 if self.verbose:
-                    print name, homes
+                    print(name, homes)
                 for home in homes:
                     paths.add(home)
                 for principal in (yield self.getProxyFor()):
                     name, homes = (yield self.getPrincipalDetails(principal,
                         includeCardDAV=False))
                     if self.verbose:
-                        print name, homes
+                        print(name, homes)
                     for home in homes:
                         if home.startswith("/"):
                             # Only support homes on the same server for now.
@@ -371,11 +372,11 @@
             if subscribeNodes:
                 self.startMonitoring(host, port, subscribeNodes)
             else:
-                print "No nodes to monitor"
+                print("No nodes to monitor")
                 reactor.stop()
 
         except Exception, e:
-            print "Error:", e
+            print("Error:", e)
             reactor.stop()
 
     @inlineCallbacks
@@ -434,12 +435,12 @@
                                         name = displayName
 
             except Exception, e:
-                print "Unable to parse principal details", e
-                print responseBody
+                print("Unable to parse principal details", e)
+                print(responseBody)
                 raise
 
         except Exception, e:
-            print "Unable to look up principal details", e
+            print("Unable to look up principal details", e)
             raise
 
         returnValue( (name, homes) )
@@ -489,12 +490,12 @@
                                                 proxies.add(href)
 
             except Exception, e:
-                print "Unable to parse proxy information", e
-                print responseBody
+                print("Unable to parse proxy information", e)
+                print(responseBody)
                 raise
 
         except Exception, e:
-            print "Unable to look up who %s is a proxy for" % (self.username,)
+            print("Unable to look up who %s is a proxy for" % (self.username,))
             raise
 
         returnValue(proxies)
@@ -561,7 +562,7 @@
                                 pushTransports = prop.find("{http://calendarserver.org/ns/}push-transports")
                                 if pushTransports is not None:
                                     if self.verbose:
-                                        print "push-transports:\n\n", ElementTree.tostring(pushTransports)
+                                        print("push-transports:\n\n", ElementTree.tostring(pushTransports))
                                     for transport in pushTransports.findall("{http://calendarserver.org/ns/}transport"):
                                         if transport.attrib["type"] == "XMPP":
                                             xmppServer = transport.find("{http://calendarserver.org/ns/}xmpp-server")
@@ -579,12 +580,12 @@
                         nodes[key] = (href.text, name, kind)
 
             except Exception, e:
-                print "Unable to parse push information", e
-                print responseBody
+                print("Unable to parse push information", e)
+                print(responseBody)
                 raise
 
         except Exception, e:
-            print "Unable to look up push information for %s" % (self.username,)
+            print("Unable to look up push information for %s" % (self.username,))
             raise
 
         if host is None:

Modified: CalendarServer/trunk/calendarserver/tools/obliterate.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/obliterate.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/obliterate.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool scans wipes out user data without using slow store object apis
@@ -43,8 +44,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         ObliterateOptions().opt_help()
     except SystemExit:

Modified: CalendarServer/trunk/calendarserver/tools/principals.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/principals.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/principals.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys
 import os
@@ -49,49 +50,49 @@
 def usage(e=None):
     if e:
         if isinstance(e, UnknownRecordTypeError):
-            print "Valid record types:"
+            print("Valid record types:")
             for recordType in config.directory.recordTypes():
-                print "    %s" % (recordType,)
+                print("    %s" % (recordType,))
 
-        print e
-        print ""
+        print(e)
+        print("")
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] action_flags principal [principal ...]" % (name,)
-    print "       %s [options] --list-principal-types" % (name,)
-    print "       %s [options] --list-principals type" % (name,)
-    print ""
-    print "  Performs the given actions against the giving principals."
-    print ""
-    print "  Principals are identified by one of the following:"
-    print "    Type and shortname (eg.: users:wsanchez)"
-    #print "    A principal path (eg.: /principals/users/wsanchez/)"
-    print "    A GUID (eg.: E415DBA7-40B5-49F5-A7CC-ACC81E4DEC79)"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -v --verbose: print debugging information"
-    print ""
-    print "actions:"
-    print "  --search <search-string>: search for matching principals"
-    print "  --list-principal-types: list all of the known principal types"
-    print "  --list-principals type: list all principals of the given type"
-    print "  --read-property=property: read DAV property (eg.: {DAV:}group-member-set)"
-    print "  --list-read-proxies: list proxies with read-only access"
-    print "  --list-write-proxies: list proxies with read-write access"
-    print "  --list-proxies: list all proxies"
-    print "  --add-read-proxy=principal: add a read-only proxy"
-    print "  --add-write-proxy=principal: add a read-write proxy"
-    print "  --remove-proxy=principal: remove a proxy"
-    print "  --set-auto-schedule={true|false}: set auto-accept state"
-    print "  --get-auto-schedule: read auto-schedule state"
-    print "  --set-auto-schedule-mode={default|none|accept-always|decline-always|accept-if-free|decline-if-busy|automatic}: set auto-schedule mode"
-    print "  --get-auto-schedule-mode: read auto-schedule mode"
-    print "  --set-auto-accept-group=principal: set auto-accept-group"
-    print "  --get-auto-accept-group: read auto-accept-group"
-    print "  --add {locations|resources} 'full name' [record name] [GUID]: add a principal"
-    print "  --remove: remove a principal"
+    print("usage: %s [options] action_flags principal [principal ...]" % (name,))
+    print("       %s [options] --list-principal-types" % (name,))
+    print("       %s [options] --list-principals type" % (name,))
+    print("")
+    print("  Performs the given actions against the giving principals.")
+    print("")
+    print("  Principals are identified by one of the following:")
+    print("    Type and shortname (eg.: users:wsanchez)")
+    #print("    A principal path (eg.: /principals/users/wsanchez/)")
+    print("    A GUID (eg.: E415DBA7-40B5-49F5-A7CC-ACC81E4DEC79)")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -v --verbose: print debugging information")
+    print("")
+    print("actions:")
+    print("  --search <search-string>: search for matching principals")
+    print("  --list-principal-types: list all of the known principal types")
+    print("  --list-principals type: list all principals of the given type")
+    print("  --read-property=property: read DAV property (eg.: {DAV:}group-member-set)")
+    print("  --list-read-proxies: list proxies with read-only access")
+    print("  --list-write-proxies: list proxies with read-write access")
+    print("  --list-proxies: list all proxies")
+    print("  --add-read-proxy=principal: add a read-only proxy")
+    print("  --add-write-proxy=principal: add a read-write proxy")
+    print("  --remove-proxy=principal: remove a proxy")
+    print("  --set-auto-schedule={true|false}: set auto-accept state")
+    print("  --get-auto-schedule: read auto-schedule state")
+    print("  --set-auto-schedule-mode={default|none|accept-always|decline-always|accept-if-free|decline-if-busy|automatic}: set auto-schedule mode")
+    print("  --get-auto-schedule-mode: read auto-schedule mode")
+    print("  --set-auto-accept-group=principal: set auto-accept-group")
+    print("  --get-auto-accept-group: read auto-accept-group")
+    print("  --add {locations|resources} 'full name' [record name] [GUID]: add a principal")
+    print("  --remove: remove a principal")
 
     if e:
         sys.exit(64)
@@ -298,7 +299,7 @@
             usage("Too many arguments")
 
         for recordType in config.directory.recordTypes():
-            print recordType
+            print(recordType)
 
         return
 
@@ -307,13 +308,13 @@
         try:
             addType = matchStrings(addType, ["locations", "resources"])
         except ValueError, e:
-            print e
+            print(e)
             return
 
         try:
             fullName, shortName, guid = parseCreationArgs(args)
         except ValueError, e:
-            print e
+            print(e)
             return
 
         if shortName is not None:
@@ -329,7 +330,7 @@
             listPrincipals = matchStrings(listPrincipals, ["users", "groups",
                 "locations", "resources"])
         except ValueError, e:
-            print e
+            print(e)
             return
 
         if args:
@@ -340,7 +341,7 @@
             if records:
                 printRecordList(records)
             else:
-                print "No records of type %s" % (listPrincipals,)
+                print("No records of type %s" % (listPrincipals,))
         except UnknownRecordTypeError, e:
             usage(e)
 
@@ -390,7 +391,7 @@
             # Performs requested actions
             for action in actions:
                 (yield action[0](principal, *action[1:]))
-                print ""
+                print("")
 
     finally:
         #
@@ -409,25 +410,25 @@
         records = list((yield config.directory.recordsMatchingTokens(searchTerm.strip().split())))
         if records:
             records.sort(key=operator.attrgetter('fullName'))
-            print "%d matches found:" % (len(records),)
+            print("%d matches found:" % (len(records),))
             for record in records:
-                print "\n%s (%s)" % (record.fullName,
+                print("\n%s (%s)" % (record.fullName,
                     { "users"     : "User",
                       "groups"    : "Group",
                       "locations" : "Place",
                       "resources" : "Resource",
                     }.get(record.recordType),
-                )
-                print "   GUID: %s" % (record.guid,)
-                print "   Record name(s): %s" % (", ".join(record.shortNames),)
+                ))
+                print("   GUID: %s" % (record.guid,))
+                print("   Record name(s): %s" % (", ".join(record.shortNames),))
                 if record.authIDs:
-                    print "   Auth ID(s): %s" % (", ".join(record.authIDs),)
+                    print("   Auth ID(s): %s" % (", ".join(record.authIDs),))
                 if record.emailAddresses:
-                    print "   Email(s): %s" % (", ".join(record.emailAddresses),)
+                    print("   Email(s): %s" % (", ".join(record.emailAddresses),))
         else:
-            print "No matches found"
+            print("No matches found")
 
-        print ""
+        print("")
 
     finally:
         #
@@ -441,9 +442,9 @@
         try:
             yield updateRecord(True, config.directory, addType, guid=guid,
                 shortNames=shortNames, fullName=fullName)
-            print "Added '%s'" % (fullName,)
+            print("Added '%s'" % (fullName,))
         except DirectoryError, e:
-            print e
+            print(e)
 
     finally:
         #
@@ -523,32 +524,32 @@
     guid = record.guid
 
     config.directory.destroyRecord(record.recordType, guid=guid)
-    print "Removed '%s' %s %s" % (fullName, shortName, guid)
+    print("Removed '%s' %s %s" % (fullName, shortName, guid))
 
 
 @inlineCallbacks
 def action_readProperty(resource, qname):
     property = (yield resource.readProperty(qname, None))
-    print "%r on %s:" % (encodeXMLName(*qname), resource)
-    print ""
-    print property.toxml()
+    print("%r on %s:" % (encodeXMLName(*qname), resource))
+    print("")
+    print(property.toxml())
 
 @inlineCallbacks
 def action_listProxies(principal, *proxyTypes):
     for proxyType in proxyTypes:
         subPrincipal = proxySubprincipal(principal, proxyType)
         if subPrincipal is None:
-            print "No %s proxies for %s" % (proxyType,
-                prettyPrincipal(principal))
+            print("No %s proxies for %s" % (proxyType,
+                prettyPrincipal(principal)))
             continue
 
         membersProperty = (yield subPrincipal.readProperty(davxml.GroupMemberSet, None))
 
         if membersProperty.children:
-            print "%s proxies for %s:" % (
+            print("%s proxies for %s:" % (
                 {"read": "Read-only", "write": "Read/write"}[proxyType],
                 prettyPrincipal(principal)
-            )
+            ))
             records = []
             for member in membersProperty.children:
                 proxyPrincipal = principalForPrincipalID(str(member),
@@ -558,15 +559,15 @@
             printRecordList(records)
             print
         else:
-            print "No %s proxies for %s" % (proxyType,
-                prettyPrincipal(principal))
+            print("No %s proxies for %s" % (proxyType,
+                prettyPrincipal(principal)))
 
 @inlineCallbacks
 def action_addProxy(principal, proxyType, *proxyIDs):
     for proxyID in proxyIDs:
         proxyPrincipal = principalForPrincipalID(proxyID)
         if proxyPrincipal is None:
-            print "Invalid principal ID: %s" % (proxyID,)
+            print("Invalid principal ID: %s" % (proxyID,))
         else:
             (yield action_addProxyPrincipal(principal, proxyType, proxyPrincipal))
 
@@ -574,13 +575,13 @@
 def action_addProxyPrincipal(principal, proxyType, proxyPrincipal):
     try:
         (yield addProxy(principal, proxyType, proxyPrincipal))
-        print "Added %s as a %s proxy for %s" % (
+        print("Added %s as a %s proxy for %s" % (
             prettyPrincipal(proxyPrincipal), proxyType,
-            prettyPrincipal(principal))
+            prettyPrincipal(principal)))
     except ProxyError, e:
-        print "Error:", e
+        print("Error:", e)
     except ProxyWarning, e:
-        print e
+        print(e)
 
 @inlineCallbacks
 def addProxy(principal, proxyType, proxyPrincipal):
@@ -671,7 +672,7 @@
     for proxyID in proxyIDs:
         proxyPrincipal = principalForPrincipalID(proxyID)
         if proxyPrincipal is None:
-            print "Invalid principal ID: %s" % (proxyID,)
+            print("Invalid principal ID: %s" % (proxyID,))
         else:
             (yield action_removeProxyPrincipal(principal, proxyPrincipal, **kwargs))
 
@@ -680,13 +681,13 @@
     try:
         removed = (yield removeProxy(principal, proxyPrincipal, **kwargs))
         if removed:
-            print "Removed %s as a proxy for %s" % (
+            print("Removed %s as a proxy for %s" % (
                 prettyPrincipal(proxyPrincipal),
-                prettyPrincipal(principal))
+                prettyPrincipal(principal)))
     except ProxyError, e:
-        print "Error:", e
+        print("Error:", e)
     except ProxyWarning, e:
-        print e
+        print(e)
 
 
 @inlineCallbacks
@@ -725,16 +726,16 @@
 @inlineCallbacks
 def action_setAutoSchedule(principal, autoSchedule):
     if principal.record.recordType == "groups":
-        print "Enabling auto-schedule for %s is not allowed." % (principal,)
+        print("Enabling auto-schedule for %s is not allowed." % (principal,))
 
     elif principal.record.recordType == "users" and not config.Scheduling.Options.AutoSchedule.AllowUsers:
-        print "Enabling auto-schedule for %s is not allowed." % (principal,)
+        print("Enabling auto-schedule for %s is not allowed." % (principal,))
 
     else:
-        print "Setting auto-schedule to %s for %s" % (
+        print("Setting auto-schedule to %s for %s" % (
             { True: "true", False: "false" }[autoSchedule],
             prettyPrincipal(principal),
-        )
+        ))
 
         (yield updateRecord(False, config.directory,
             principal.record.recordType,
@@ -747,24 +748,24 @@
 
 def action_getAutoSchedule(principal):
     autoSchedule = principal.getAutoSchedule()
-    print "Auto-schedule for %s is %s" % (
+    print("Auto-schedule for %s is %s" % (
         prettyPrincipal(principal),
         { True: "true", False: "false" }[autoSchedule],
-    )
+    ))
 
 @inlineCallbacks
 def action_setAutoScheduleMode(principal, autoScheduleMode):
     if principal.record.recordType == "groups":
-        print "Setting auto-schedule mode for %s is not allowed." % (principal,)
+        print("Setting auto-schedule mode for %s is not allowed." % (principal,))
 
     elif principal.record.recordType == "users" and not config.Scheduling.Options.AutoSchedule.AllowUsers:
-        print "Setting auto-schedule mode for %s is not allowed." % (principal,)
+        print("Setting auto-schedule mode for %s is not allowed." % (principal,))
 
     else:
-        print "Setting auto-schedule mode to %s for %s" % (
+        print("Setting auto-schedule mode to %s for %s" % (
             autoScheduleMode,
             prettyPrincipal(principal),
-        )
+        ))
 
         (yield updateRecord(False, config.directory,
             principal.record.recordType,
@@ -779,28 +780,28 @@
     autoScheduleMode = principal.getAutoScheduleMode()
     if not autoScheduleMode:
         autoScheduleMode = "automatic"
-    print "Auto-schedule mode for %s is %s" % (
+    print("Auto-schedule mode for %s is %s" % (
         prettyPrincipal(principal),
         autoScheduleMode,
-    )
+    ))
 
 @inlineCallbacks
 def action_setAutoAcceptGroup(principal, autoAcceptGroup):
     if principal.record.recordType == "groups":
-        print "Setting auto-accept-group for %s is not allowed." % (principal,)
+        print("Setting auto-accept-group for %s is not allowed." % (principal,))
 
     elif principal.record.recordType == "users" and not config.Scheduling.Options.AutoSchedule.AllowUsers:
-        print "Setting auto-accept-group for %s is not allowed." % (principal,)
+        print("Setting auto-accept-group for %s is not allowed." % (principal,))
 
     else:
         groupPrincipal = principalForPrincipalID(autoAcceptGroup)
         if groupPrincipal is None or groupPrincipal.record.recordType != "groups":
-            print "Invalid principal ID: %s" % (autoAcceptGroup,)
+            print("Invalid principal ID: %s" % (autoAcceptGroup,))
         else:
-            print "Setting auto-accept-group to %s for %s" % (
+            print("Setting auto-accept-group to %s for %s" % (
                 prettyPrincipal(groupPrincipal),
                 prettyPrincipal(principal),
-            )
+            ))
 
             (yield updateRecord(False, config.directory,
                 principal.record.recordType,
@@ -818,14 +819,14 @@
         if record is not None:
             groupPrincipal = config.directory.principalCollection.principalForUID(record.uid)
             if groupPrincipal is not None:
-                print "Auto-accept-group for %s is %s" % (
+                print("Auto-accept-group for %s is %s" % (
                     prettyPrincipal(principal),
                     prettyPrincipal(groupPrincipal),
-                )
+                ))
                 return
-        print "Invalid auto-accept-group assigned: %s" % (autoAcceptGroup,)
+        print("Invalid auto-accept-group assigned: %s" % (autoAcceptGroup,))
     else:
-        print "No auto-accept-group assigned to %s" % (prettyPrincipal(principal),)
+        print("No auto-accept-group assigned to %s" % (prettyPrincipal(principal),))
 
 
 def abort(msg, status=1):
@@ -894,10 +895,10 @@
         for record in records]
     results.sort()
     format = "%-22s %-17s %s"
-    print format % ("Full name", "Record name", "UUID")
-    print format % ("---------", "-----------", "----")
+    print(format % ("Full name", "Record name", "UUID"))
+    print(format % ("---------", "-----------", "----"))
     for fullName, shortName, guid in results:
-        print format % (fullName, shortName, guid)
+        print(format % (fullName, shortName, guid))
 
 def prettyPrincipal(principal):
     record = principal.record

Modified: CalendarServer/trunk/calendarserver/tools/purge.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/purge.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/purge.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.tap.util import FakeRequest
 from calendarserver.tap.util import getRootResource
@@ -107,19 +108,19 @@
     def usage(cls, e=None):
 
         name = os.path.basename(sys.argv[0])
-        print "usage: %s [options]" % (name,)
-        print ""
-        print "  Remove old events from the calendar server"
-        print ""
-        print "options:"
-        print "  -h --help: print this help and exit"
-        print "  -f --config <path>: Specify caldavd.plist configuration path"
-        print "  -d --days <number>: specify how many days in the past to retain (default=%d)" % (DEFAULT_RETAIN_DAYS,)
-        #print "  -b --batch <number>: number of events to remove in each transaction (default=%d)" % (DEFAULT_BATCH_SIZE,)
-        print "  -n --dry-run: calculate how many events to purge, but do not purge data"
-        print "  -v --verbose: print progress information"
-        print "  -D --debug: debug logging"
-        print ""
+        print("usage: %s [options]" % (name,))
+        print("")
+        print("  Remove old events from the calendar server")
+        print("")
+        print("options:")
+        print("  -h --help: print this help and exit")
+        print("  -f --config <path>: Specify caldavd.plist configuration path")
+        print("  -d --days <number>: specify how many days in the past to retain (default=%d)" % (DEFAULT_RETAIN_DAYS,))
+        #print("  -b --batch <number>: number of events to remove in each transaction (default=%d)" % (DEFAULT_BATCH_SIZE,))
+        print("  -n --dry-run: calculate how many events to purge, but do not purge data")
+        print("  -v --verbose: print progress information")
+        print("  -D --debug: debug logging")
+        print("")
 
         if e:
             sys.stderr.write("%s\n" % (e,))
@@ -164,14 +165,14 @@
                 try:
                     days = int(arg)
                 except ValueError, e:
-                    print "Invalid value for --days: %s" % (arg,)
+                    print("Invalid value for --days: %s" % (arg,))
                     cls.usage(e)
 
             elif opt in ("-b", "--batch"):
                 try:
                     batchSize = int(arg)
                 except ValueError, e:
-                    print "Invalid value for --batch: %s" % (arg,)
+                    print("Invalid value for --batch: %s" % (arg,))
                     cls.usage(e)
 
             elif opt in ("-v", "--verbose"):
@@ -228,21 +229,21 @@
 
         if self.dryrun:
             if self.verbose:
-                print "(Dry run) Searching for old events..."
+                print("(Dry run) Searching for old events...")
             txn = self._store.newTransaction(label="Find old events")
             oldEvents = (yield txn.eventsOlderThan(self.cutoff))
             eventCount = len(oldEvents)
             if self.verbose:
                 if eventCount == 0:
-                    print "No events are older than %s" % (self.cutoff,)
+                    print("No events are older than %s" % (self.cutoff,))
                 elif eventCount == 1:
-                    print "1 event is older than %s" % (self.cutoff,)
+                    print("1 event is older than %s" % (self.cutoff,))
                 else:
-                    print "%d events are older than %s" % (eventCount, self.cutoff)
+                    print("%d events are older than %s" % (eventCount, self.cutoff))
             returnValue(eventCount)
 
         if self.verbose:
-            print "Removing events older than %s..." % (self.cutoff,)
+            print("Removing events older than %s..." % (self.cutoff,))
 
         numEventsRemoved = -1
         totalRemoved = 0
@@ -253,16 +254,16 @@
             if numEventsRemoved:
                 totalRemoved += numEventsRemoved
                 if self.verbose:
-                    print "%d," % (totalRemoved,),
+                    print("%d," % (totalRemoved,),)
 
         if self.verbose:
-            print
+            print("")
             if totalRemoved == 0:
-                print "No events were removed"
+                print("No events were removed")
             elif totalRemoved == 1:
-                print "1 event was removed in total"
+                print("1 event was removed in total")
             else:
-                print "%d events were removed in total" % (totalRemoved,)
+                print("%d events were removed in total" % (totalRemoved,))
 
         returnValue(totalRemoved)
 
@@ -280,20 +281,20 @@
     def usage(cls, e=None):
 
         name = os.path.basename(sys.argv[0])
-        print "usage: %s [options]" % (name,)
-        print ""
-        print "  Remove old or orphaned attachments from the calendar server"
-        print ""
-        print "options:"
-        print "  -h --help: print this help and exit"
-        print "  -f --config <path>: Specify caldavd.plist configuration path"
-        print "  -u --uuid <owner uid>: target a specific user UID"
-        #print "  -b --batch <number>: number of attachments to remove in each transaction (default=%d)" % (DEFAULT_BATCH_SIZE,)
-        print "  -d --days <number>: specify how many days in the past to retain (default=%d) zero means no removal of old attachments" % (DEFAULT_RETAIN_DAYS,)
-        print "  -n --dry-run: calculate how many attachments to purge, but do not purge data"
-        print "  -v --verbose: print progress information"
-        print "  -D --debug: debug logging"
-        print ""
+        print("usage: %s [options]" % (name,))
+        print("")
+        print("  Remove old or orphaned attachments from the calendar server")
+        print("")
+        print("options:")
+        print("  -h --help: print this help and exit")
+        print("  -f --config <path>: Specify caldavd.plist configuration path")
+        print("  -u --uuid <owner uid>: target a specific user UID")
+        #print("  -b --batch <number>: number of attachments to remove in each transaction (default=%d)" % (DEFAULT_BATCH_SIZE,))
+        print("  -d --days <number>: specify how many days in the past to retain (default=%d) zero means no removal of old attachments" % (DEFAULT_RETAIN_DAYS,))
+        print("  -n --dry-run: calculate how many attachments to purge, but do not purge data")
+        print("  -v --verbose: print progress information")
+        print("  -D --debug: debug logging")
+        print("")
 
         if e:
             sys.stderr.write("%s\n" % (e,))
@@ -343,14 +344,14 @@
                 try:
                     days = int(arg)
                 except ValueError, e:
-                    print "Invalid value for --days: %s" % (arg,)
+                    print("Invalid value for --days: %s" % (arg,))
                     cls.usage(e)
 
             elif opt in ("-b", "--batch"):
                 try:
                     batchSize = int(arg)
                 except ValueError, e:
-                    print "Invalid value for --batch: %s" % (arg,)
+                    print("Invalid value for --batch: %s" % (arg,))
                     cls.usage(e)
 
             elif opt in ("-v", "--verbose"):
@@ -438,7 +439,7 @@
     def _orphansDryRun(self):
 
         if self.verbose:
-            print "(Dry run) Searching for orphaned attachments..."
+            print("(Dry run) Searching for orphaned attachments...")
         txn = self._store.newTransaction(label="Find orphaned attachments")
         orphans = (yield txn.orphanedAttachments(self.uuid))
         returnValue(orphans)
@@ -448,7 +449,7 @@
     def _dropboxDryRun(self):
 
         if self.verbose:
-            print "(Dry run) Searching for old dropbox attachments..."
+            print("(Dry run) Searching for old dropbox attachments...")
         txn = self._store.newTransaction(label="Find old dropbox attachments")
         cutoffs = (yield txn.oldDropboxAttachments(self.cutoff, self.uuid))
         yield txn.commit()
@@ -460,7 +461,7 @@
     def _managedDryRun(self):
 
         if self.verbose:
-            print "(Dry run) Searching for old managed attachments..."
+            print("(Dry run) Searching for old managed attachments...")
         txn = self._store.newTransaction(label="Find old managed attachments")
         cutoffs = (yield txn.oldManagedAttachments(self.cutoff, self.uuid))
         yield txn.commit()
@@ -525,8 +526,8 @@
             table.addFooter(("Total:", "",) + tuple(totals))
             total = totals[7]
 
-            print "\n"
-            print "Orphaned/Old Attachments by User:\n"
+            print("\n")
+            print("Orphaned/Old Attachments by User:\n")
             table.printTable()
         else:
             total = sum([x[3] for x in orphans]) + sum([x[3] for x in dropbox]) + sum([x[3] for x in managed])
@@ -538,7 +539,7 @@
     def _orphansPurge(self):
 
         if self.verbose:
-            print "Removing orphaned attachments...",
+            print("Removing orphaned attachments...",)
 
         numOrphansRemoved = -1
         totalRemoved = 0
@@ -549,18 +550,18 @@
             if numOrphansRemoved:
                 totalRemoved += numOrphansRemoved
                 if self.verbose:
-                    print " %d," % (totalRemoved,),
+                    print(" %d," % (totalRemoved,),)
             elif self.verbose:
-                print
+                print("")
 
         if self.verbose:
             if totalRemoved == 0:
-                print "No orphaned attachments were removed"
+                print("No orphaned attachments were removed")
             elif totalRemoved == 1:
-                print "1 orphaned attachment was removed in total"
+                print("1 orphaned attachment was removed in total")
             else:
-                print "%d orphaned attachments were removed in total" % (totalRemoved,)
-            print
+                print("%d orphaned attachments were removed in total" % (totalRemoved,))
+            print("")
 
         returnValue(totalRemoved)
 
@@ -569,7 +570,7 @@
     def _dropboxPurge(self):
 
         if self.verbose:
-            print "Removing old dropbox attachments...",
+            print("Removing old dropbox attachments...",)
 
         numOldRemoved = -1
         totalRemoved = 0
@@ -580,18 +581,18 @@
             if numOldRemoved:
                 totalRemoved += numOldRemoved
                 if self.verbose:
-                    print " %d," % (totalRemoved,),
+                    print(" %d," % (totalRemoved,),)
             elif self.verbose:
-                print
+                print("")
 
         if self.verbose:
             if totalRemoved == 0:
-                print "No old dropbox attachments were removed"
+                print("No old dropbox attachments were removed")
             elif totalRemoved == 1:
-                print "1 old dropbox attachment was removed in total"
+                print("1 old dropbox attachment was removed in total")
             else:
-                print "%d old dropbox attachments were removed in total" % (totalRemoved,)
-            print
+                print("%d old dropbox attachments were removed in total" % (totalRemoved,))
+            print("")
 
         returnValue(totalRemoved)
 
@@ -600,7 +601,7 @@
     def _managedPurge(self):
 
         if self.verbose:
-            print "Removing old managed attachments...",
+            print("Removing old managed attachments...",)
 
         numOldRemoved = -1
         totalRemoved = 0
@@ -611,18 +612,18 @@
             if numOldRemoved:
                 totalRemoved += numOldRemoved
                 if self.verbose:
-                    print " %d," % (totalRemoved,),
+                    print(" %d," % (totalRemoved,),)
             elif self.verbose:
-                print
+                print("")
 
         if self.verbose:
             if totalRemoved == 0:
-                print "No old managed attachments were removed"
+                print("No old managed attachments were removed")
             elif totalRemoved == 1:
-                print "1 old managed attachment was removed in total"
+                print("1 old managed attachment was removed in total")
             else:
-                print "%d old managed attachments were removed in total" % (totalRemoved,)
-            print
+                print("%d old managed attachments were removed in total" % (totalRemoved,))
+            print("")
 
         returnValue(totalRemoved)
 
@@ -644,18 +645,18 @@
     def usage(cls, e=None):
 
         name = os.path.basename(sys.argv[0])
-        print "usage: %s [options]" % (name,)
-        print ""
-        print "  Remove a principal's events and contacts from the calendar server"
-        print ""
-        print "options:"
-        print "  -c --completely: By default, only future events are canceled; this option cancels all events"
-        print "  -h --help: print this help and exit"
-        print "  -f --config <path>: Specify caldavd.plist configuration path"
-        print "  -n --dry-run: calculate how many events and contacts to purge, but do not purge data"
-        print "  -v --verbose: print progress information"
-        print "  -D --debug: debug logging"
-        print ""
+        print("usage: %s [options]" % (name,))
+        print("")
+        print("  Remove a principal's events and contacts from the calendar server")
+        print("")
+        print("options:")
+        print("  -c --completely: By default, only future events are canceled; this option cancels all events")
+        print("  -h --help: print this help and exit")
+        print("  -f --config <path>: Specify caldavd.plist configuration path")
+        print("  -n --dry-run: calculate how many events and contacts to purge, but do not purge data")
+        print("  -v --verbose: print progress information")
+        print("  -D --debug: debug logging")
+        print("")
 
         if e:
             sys.stderr.write("%s\n" % (e,))
@@ -769,9 +770,9 @@
         if self.verbose:
             amount = "%d event%s" % (total, "s" if total > 1 else "")
             if self.dryrun:
-                print "Would have modified or deleted %s" % (amount,)
+                print("Would have modified or deleted %s" % (amount,))
             else:
-                print "Modified or deleted %s" % (amount,)
+                print("Modified or deleted %s" % (amount,))
 
         returnValue((total, allAssignments,))
 
@@ -819,9 +820,9 @@
             for child in children:
                 if self.verbose:
                     if self.dryrun:
-                        print "Would unshare: %s" % (child.name(),)
+                        print("Would unshare: %s" % (child.name(),))
                     else:
-                        print "Unsharing: %s" % (child.name(),)
+                        print("Unsharing: %s" % (child.name(),))
                 if not self.dryrun:
                     (yield child.unshare())
 
@@ -895,9 +896,9 @@
                                 )
                                 if self.verbose:
                                     if self.dryrun:
-                                        print "Would modify: %s" % (uri,)
+                                        print("Would modify: %s" % (uri,))
                                     else:
-                                        print "Modifying: %s" % (uri,)
+                                        print("Modifying: %s" % (uri,))
                                 if not self.dryrun:
                                     result = (yield storer.run())
 
@@ -906,37 +907,37 @@
                                 request._rememberResource(childResource, uri)
                                 if self.verbose:
                                     if self.dryrun:
-                                        print "Would delete: %s" % (uri,)
+                                        print("Would delete: %s" % (uri,))
                                     else:
-                                        print "Deleting: %s" % (uri,)
+                                        print("Deleting: %s" % (uri,))
                                 if not self.dryrun:
                                     retry = False
                                     try:
                                         result = (yield childResource.storeRemove(request, self.doimplicit, uri))
                                         if result != NO_CONTENT:
-                                            print "Error deleting %s/%s/%s: %s" % (uid,
-                                                collName, childName, result)
+                                            print("Error deleting %s/%s/%s: %s" % (uid,
+                                                collName, childName, result))
                                             retry = True
                                         else:
                                             incrementCount = True
 
                                     except Exception, e:
-                                        print "Exception deleting %s/%s/%s: %s" % (uid,
-                                            collName, childName, str(e))
+                                        print("Exception deleting %s/%s/%s: %s" % (uid,
+                                            collName, childName, str(e)))
                                         retry = True
 
                                     if retry and self.doimplicit:
                                         # Try again with implicit scheduling off
-                                        print "Retrying deletion of %s/%s/%s with implicit scheduling turned off" % (uid, collName, childName)
+                                        print("Retrying deletion of %s/%s/%s with implicit scheduling turned off" % (uid, collName, childName))
                                         try:
                                             result = (yield childResource.storeRemove(request, False, uri))
                                             if result != NO_CONTENT:
-                                                print "Error deleting %s/%s/%s: %s" % (uid,
-                                                    collName, childName, result)
+                                                print("Error deleting %s/%s/%s: %s" % (uid,
+                                                    collName, childName, result))
                                             else:
                                                 incrementCount = True
                                         except Exception, e:
-                                            print "Still couldn't delete %s/%s/%s even with implicit scheduling turned off: %s" % (uid, collName, childName, str(e))
+                                            print("Still couldn't delete %s/%s/%s even with implicit scheduling turned off: %s" % (uid, collName, childName, str(e)))
 
                                 if incrementCount:
                                     count += 1
@@ -968,18 +969,18 @@
                         calendarName = calColl.name()
                         if self.verbose:
                             if self.dryrun:
-                                print "Would delete calendar: %s" % (calendarName,)
+                                print("Would delete calendar: %s" % (calendarName,))
                             else:
-                                print "Deleting calendar: %s" % (calendarName,)
+                                print("Deleting calendar: %s" % (calendarName,))
                         if not self.dryrun:
                             (yield storeCalHome.removeChildWithName(calendarName))
 
                 if not remainingCalendars:
                     if self.verbose:
                         if self.dryrun:
-                            print "Would delete calendar home"
+                            print("Would delete calendar home")
                         else:
-                            print "Deleting calendar home"
+                            print("Deleting calendar home")
                     if not self.dryrun:
                         (yield storeCalHome.remove())
 
@@ -992,27 +993,27 @@
                         if self.verbose:
                             uri = "/addressbooks/__uids__/%s/%s/%s" % (uid, abColl.name(), cardName)
                             if self.dryrun:
-                                print "Would delete: %s" % (uri,)
+                                print("Would delete: %s" % (uri,))
                             else:
-                                print "Deleting: %s" % (uri,)
+                                print("Deleting: %s" % (uri,))
                         if not self.dryrun:
                             (yield abColl.removeObjectResourceWithName(cardName))
                         count += 1
                     if self.verbose:
                         abName = abColl.name()
                         if self.dryrun:
-                            print "Would delete addressbook: %s" % (abName,)
+                            print("Would delete addressbook: %s" % (abName,))
                         else:
-                            print "Deleting addressbook: %s" % (abName,)
+                            print("Deleting addressbook: %s" % (abName,))
                     if not self.dryrun:
                         # Also remove the addressbook collection itself
                         (yield storeAbHome.removeChildWithName(abColl.name()))
 
                 if self.verbose:
                     if self.dryrun:
-                        print "Would delete addressbook home"
+                        print("Would delete addressbook home")
                     else:
-                        print "Deleting addressbook home"
+                        print("Deleting addressbook home")
                 if not self.dryrun:
                     (yield storeAbHome.remove())
 
@@ -1026,7 +1027,7 @@
 
         if self.proxies and not self.dryrun:
             if self.verbose:
-                print "Deleting any proxy assignments"
+                print("Deleting any proxy assignments")
             assignments = (yield self._purgeProxyAssignments(principal))
 
         returnValue((count, assignments))

Modified: CalendarServer/trunk/calendarserver/tools/push.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/push.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/push.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.tap.util import getRootResource
 from calendarserver.tools.cmdline import utilityMain
@@ -33,15 +34,15 @@
 def usage(e=None):
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] [user ...]" % (name,)
-    print ""
-    print "  Display Apple Push Notification subscriptions"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -D --debug: debug logging"
-    print ""
+    print("usage: %s [options] [user ...]" % (name,))
+    print("")
+    print("  Display Apple Push Notification subscriptions")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -D --debug: debug logging")
+    print("")
 
     if e:
         sys.stderr.write("%s\n" % (e,))
@@ -157,7 +158,7 @@
         print
         record = directory.recordWithShortName("users", user)
         if record is not None:
-            print "User %s (%s)..." % (user, record.uid)
+            print("User %s (%s)..." % (user, record.uid))
             txn = store.newTransaction(label="Display APN Subscriptions")
             subscriptions = (yield txn.apnSubscriptionsBySubscriber(record.uid))
             (yield txn.commit())
@@ -180,15 +181,20 @@
                     record = directory.recordWithUID(uid)
                     user = record.shortNames[0]
                     if collection:
-                        print "...is subscribed to a share from %s's %s home" % (user, resource),
+                        print("...is subscribed to a share from %s's %s home" % (user, resource),)
                     else:
-                        print "...is subscribed to %s's %s home" % (user, resource),
-                        # print "   (key: %s)\n" % (key,)
-                    print "with %d device(s):" % (len(tokens),)
+                        print("...is subscribed to %s's %s home" % (user, resource),)
+                        # print("   (key: %s)\n" % (key,))
+                    print("with %d device(s):" % (len(tokens),))
                     for token, timestamp, userAgent, ipAddr in tokens:
-                        print " %s\n   '%s' from %s\n   %s" % (token, userAgent, ipAddr,
-                            time.strftime("on %a, %d %b %Y at %H:%M:%S %z(%Z)", time.localtime(timestamp)))
+                        print(" %s\n   '%s' from %s\n   %s" % (
+                            token, userAgent, ipAddr,
+                            time.strftime(
+                                "on %a, %d %b %Y at %H:%M:%S %z(%Z)",
+                                time.localtime(timestamp)
+                            )
+                        ))
             else:
-                print " ...is not subscribed to anything."
+                print(" ...is not subscribed to anything.")
         else:
-            print "User %s not found" % (user,)
+            print("User %s not found" % (user,))

Modified: CalendarServer/trunk/calendarserver/tools/resources.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/resources.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/resources.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from calendarserver.tools.util import loadConfig, getDirectory, setupMemcached, checkDirectory
 from getopt import getopt, GetoptError
@@ -39,15 +40,15 @@
 def usage():
 
     name = os.path.basename(sys.argv[0])
-    print "usage: %s [options] " % (name,)
-    print ""
-    print "  Migrates resources and locations from OD to Calendar Server"
-    print ""
-    print "options:"
-    print "  -h --help: print this help and exit"
-    print "  -f --config <path>: Specify caldavd.plist configuration path"
-    print "  -v --verbose: print debugging information"
-    print ""
+    print("usage: %s [options] " % (name,))
+    print("")
+    print("  Migrates resources and locations from OD to Calendar Server")
+    print("")
+    print("options:")
+    print("  -h --help: print this help and exit")
+    print("  -f --config <path>: Specify caldavd.plist configuration path")
+    print("  -v --verbose: print debugging information")
+    print("")
 
     sys.exit(0)
 
@@ -175,7 +176,7 @@
     ]
 
     if verbose:
-        print "Querying for all %s records" % (recordType,)
+        print("Querying for all %s records" % (recordType,))
 
     results = list(sourceService.odModule.listAllRecordsWithAttributes_list(
         sourceService.directory,
@@ -184,7 +185,7 @@
     ))
 
     if verbose:
-        print "Found %d records" % (len(results),)
+        print("Found %d records" % (len(results),))
 
     return results
 
@@ -210,7 +211,7 @@
                 record = destService.recordWithGUID(guid)
                 if record is None:
                     if verbose:
-                        print "Migrating %s (%s)" % (fullName, recordType)
+                        print("Migrating %s (%s)" % (fullName, recordType))
 
                     if autoSchedules is not None:
                         autoSchedule = autoSchedules.get(guid, 1)

Modified: CalendarServer/trunk/calendarserver/tools/shell/terminal.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/shell/terminal.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/shell/terminal.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Interactive shell for terminals.
@@ -56,8 +57,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         ShellOptions().opt_help()
     except SystemExit:
@@ -340,7 +341,7 @@
 
         if tokens:
             cmd = tokens.pop(0)
-            #print "Arguments: %r" % (tokens,)
+            #print("Arguments: %r" % (tokens,))
 
             m = getattr(self.commands, "cmd_%s" % (cmd,), None)
             if m:
@@ -410,6 +411,6 @@
         directory = getDirectory()
         return ShellService(store, directory, options, reactor, config)
 
-    print "Initializing shell..."
+    print("Initializing shell...")
 
     utilityMain(options["config"], makeService, reactor)

Modified: CalendarServer/trunk/calendarserver/tools/test/test_calverify.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/test/test_calverify.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/test/test_calverify.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Tests for calendarserver.tools.calverify
@@ -2364,4 +2365,4 @@
         end.offsetDay(30)
         config.MaxAllowedInstances = 3000
         i = c.expandTimeRanges(end, start, ignoreInvalidInstances=True)
-        print i
+        print(i)

Modified: CalendarServer/trunk/calendarserver/tools/test/test_gateway.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/test/test_gateway.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/test/test_gateway.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 import sys
@@ -95,7 +96,7 @@
         try:
             plist = readPlistFromString(output)
         except xml.parsers.expat.ExpatError, e:
-            print "Error (%s) parsing (%s)" % (e, output)
+            print("Error (%s) parsing (%s)" % (e, output))
             raise
 
         returnValue(plist)

Modified: CalendarServer/trunk/calendarserver/tools/upgrade.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/upgrade.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/upgrade.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool allows any necessary upgrade to complete, then exits.
@@ -38,8 +39,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         UpgradeOptions().opt_help()
     except SystemExit:
@@ -214,7 +215,7 @@
 
     def _onShutdown():
         if not UpgraderService.started:
-            print "Failed to start service."
+            print("Failed to start service.")
 
     utilityMain(options["config"], makeService, reactor, customServiceMaker, patchConfig=_patchConfig, onShutdown=_onShutdown, verbose=options["debug"])
 

Modified: CalendarServer/trunk/calendarserver/tools/validcalendardata.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/validcalendardata.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/calendarserver/tools/validcalendardata.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 This tool takes data from stdin and validates it as iCalendar data suitable
@@ -32,8 +33,8 @@
 
 def usage(e=None):
     if e:
-        print e
-        print ""
+        print(e)
+        print("")
     try:
         ValidOptions().opt_help()
     except SystemExit:
@@ -145,9 +146,9 @@
             result, message = self.validCalendarData()
 
         if result:
-            print "Calendar data OK"
+            print("Calendar data OK")
         else:
-            print message
+            print(message)
         self.reactor.stop()
 
 
@@ -167,7 +168,7 @@
             if unfixed:
                 raise InvalidICalendarDataError("Calendar data had unfixable problems:\n  %s" % ("\n  ".join(unfixed),))
             if fixed:
-                print "Calendar data had fixable problems:\n  %s" % ("\n  ".join(fixed),)
+                print("Calendar data had fixable problems:\n  %s" % ("\n  ".join(fixed),))
 
         except ValueError, e:
             result = False

Modified: CalendarServer/trunk/contrib/migration/calendarcommonextra.py
===================================================================
--- CalendarServer/trunk/contrib/migration/calendarcommonextra.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/migration/calendarcommonextra.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -9,6 +9,7 @@
 # Software License Agreement accompanying the package this file is a
 # part of.  You may not port this file to another platform without
 # Apple's written consent.
+from __future__ import print_function
 
 import datetime
 import subprocess
@@ -32,7 +33,7 @@
     try:
         timestamp = datetime.datetime.now().strftime("%b %d %H:%M:%S")
         msg = "calendarcommonextra: %s %s" % (timestamp, msg)
-        print msg # so it appears in Setup.log
+        print(msg) # so it appears in Setup.log
         with open(LOG, 'a') as output:
             output.write("%s\n" % (msg,)) # so it appears in our log
     except IOError:

Modified: CalendarServer/trunk/contrib/migration/calendardemotion.py
===================================================================
--- CalendarServer/trunk/contrib/migration/calendardemotion.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/migration/calendardemotion.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -9,6 +9,7 @@
 # Software License Agreement accompanying the package this file is a
 # part of.  You may not port this file to another platform without
 # Apple's written consent.
+from __future__ import print_function
 
 import os
 from plistlib import readPlist, writePlist
@@ -30,7 +31,7 @@
             writePlist(plistData, plistPath)
 
         except Exception, e:
-            print "Unable to disable services in %s: %s" % (plistPath, e)
+            print("Unable to disable services in %s: %s" % (plistPath, e))
 
 
 if __name__ == '__main__':

Modified: CalendarServer/trunk/contrib/migration/calendarmigrator.py
===================================================================
--- CalendarServer/trunk/contrib/migration/calendarmigrator.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/migration/calendarmigrator.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -17,7 +17,7 @@
 # Software License Agreement accompanying the package this file is a
 # part of.  You may not port this file to another platform without
 # Apple's written consent.
-
+from __future__ import print_function
 from __future__ import with_statement
 
 import datetime
@@ -513,7 +513,7 @@
     try:
         timestamp = datetime.datetime.now().strftime("%b %d %H:%M:%S")
         msg = "calendarmigrator: %s %s" % (timestamp, msg)
-        print msg # so it appears in Setup.log
+        print(msg) # so it appears in Setup.log
         with open(LOG, 'a') as output:
             output.write("%s\n" % (msg,)) # so it appears in our log
     except IOError:

Modified: CalendarServer/trunk/contrib/migration/calendarpromotion.py
===================================================================
--- CalendarServer/trunk/contrib/migration/calendarpromotion.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/migration/calendarpromotion.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -9,6 +9,7 @@
 # Software License Agreement accompanying the package this file is a
 # part of.  You may not port this file to another platform without
 # Apple's written consent.
+from __future__ import print_function
 
 import os
 import shutil
@@ -77,7 +78,7 @@
             gid = getgrnam(GROUP_NAME).gr_gid
             os.chown(dirName, uid, gid)
         except Exception, e:
-            print "Unable to chown %s: %s" % (dirName, e)
+            print("Unable to chown %s: %s" % (dirName, e))
 
 
     plistPath = os.path.join(DEST_CONFIG_DIR, CALDAVD_PLIST)
@@ -89,7 +90,7 @@
             writePlist(plistData, plistPath)
 
         except Exception, e:
-            print "Unable to disable update values in %s: %s" % (plistPath, e)
+            print("Unable to disable update values in %s: %s" % (plistPath, e))
 
     else:
         # Copy configuration

Modified: CalendarServer/trunk/contrib/migration/test/test_migrator.py
===================================================================
--- CalendarServer/trunk/contrib/migration/test/test_migrator.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/migration/test/test_migrator.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import twistedcaldav.test.util
 from contrib.migration.calendarmigrator import (
@@ -1093,7 +1094,7 @@
         ]
 
         for description, (source, target), paths, expected in info:
-            # print "-=-=-=- %s -=-=-=-" % (description,)
+            # print("-=-=-=- %s -=-=-=-" % (description,))
             accessor = StubDiskAccessor(paths)
             actual = examinePreviousSystem(source, target, diskAccessor=accessor)
             self.assertEquals(expected, actual)

Modified: CalendarServer/trunk/contrib/performance/benchlib.py
===================================================================
--- CalendarServer/trunk/contrib/performance/benchlib.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/benchlib.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import pickle
 from time import time
@@ -192,7 +193,7 @@
     msg('dtrace stopped')
     for (k, v) in leftOver.items():
         if v:
-            print 'Extra', k, ':', v
+            print('Extra', k, ':', v)
     returnValue(data)
 
 

Modified: CalendarServer/trunk/contrib/performance/benchmark.py
===================================================================
--- CalendarServer/trunk/contrib/performance/benchmark.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/benchmark.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys, os, plistlib
 from os.path import dirname
@@ -335,7 +336,7 @@
         statistics[name] = {}
         parameters = scalingParameters.get(name, [1, 9, 81])
         for p in parameters:
-            print '%s, parameter=%s' % (name, p)
+            print('%s, parameter=%s' % (name, p))
             dtrace = DTraceCollector("io_measure.d", pids)
             data = yield measure(host, port, dtrace, p, sampleTime)
             statistics[name][p] = data
@@ -446,7 +447,7 @@
     try:
         options.parseOptions(sys.argv[1:])
     except UsageError, e:
-        print e
+        print(e)
         return 1
 
     if options['debug']:

Modified: CalendarServer/trunk/contrib/performance/compare.py
===================================================================
--- CalendarServer/trunk/contrib/performance/compare.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/compare.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys
 
@@ -68,7 +69,7 @@
     p = ttest_1samp(second, fmean)[1]
     if p >= 0.95:
         # rejected the null hypothesis
-        print sys.argv[1], 'mean of', fmean, 'differs from', sys.argv[2], 'mean of', smean, '(%2.0f%%)' % (p * 100,)
+        print(sys.argv[1], 'mean of', fmean, 'differs from', sys.argv[2], 'mean of', smean, '(%2.0f%%)' % (p * 100,))
     else:
         # failed to reject the null hypothesis
-        print 'cannot prove means (%s, %s) differ (%2.0f%%)' % (fmean, smean, p * 100,)
+        print('cannot prove means (%s, %s) differ (%2.0f%%)' % (fmean, smean, p * 100,))

Modified: CalendarServer/trunk/contrib/performance/display-calendar-events.py
===================================================================
--- CalendarServer/trunk/contrib/performance/display-calendar-events.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/display-calendar-events.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,16 +13,17 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import eventkitframework as EventKit
 from Cocoa import NSDate
 
 store = EventKit.EKEventStore.alloc().init()
 calendars = store.calendarsForEntityType_(0)
-print calendars
+print(calendars)
 raise SystemExit
 
 predicate = store.predicateForEventsWithStartDate_endDate_calendars_(
      NSDate.date(), NSDate.distantFuture(),
      [calendars[2]])
-print store.eventsMatchingPredicate_(predicate)
+print(store.eventsMatchingPredicate_(predicate))

Modified: CalendarServer/trunk/contrib/performance/httpauth.py
===================================================================
--- CalendarServer/trunk/contrib/performance/httpauth.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/httpauth.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import urlparse, urllib2
 
@@ -170,8 +171,8 @@
     d = agent.request(
         'DELETE', 'http://localhost:8008/calendars/users/user01/monkeys3/')
     def deleted(response):
-        print response.code
-        print response.headers
+        print(response.code)
+        print(response.headers)
         reactor.stop()
     d.addCallback(deleted)
     d.addErrback(err)

Modified: CalendarServer/trunk/contrib/performance/loadtest/ampsim.py
===================================================================
--- CalendarServer/trunk/contrib/performance/loadtest/ampsim.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/loadtest/ampsim.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -188,4 +188,3 @@
         msg(**event)
         return {}
 
-

Modified: CalendarServer/trunk/contrib/performance/loadtest/ical.py
===================================================================
--- CalendarServer/trunk/contrib/performance/loadtest/ical.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/loadtest/ical.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # limitations under the License.
 #
 ##
+from __future__ import print_function
 
 from caldavclientlibrary.protocol.caldav.definitions import caldavxml
 from caldavclientlibrary.protocol.caldav.definitions import csxml
@@ -316,10 +317,10 @@
         self._client = client
 
     def initFailed(self, reason):
-        print 'XMPP initialization failed', reason
+        print('XMPP initialization failed', reason)
 
     def authFailed(self, reason):
-        print 'XMPP Authentication failed', reason
+        print('XMPP Authentication failed', reason)
 
     def handleMessageEventItems(self, iq):
         item = iq.firstChildElement().firstChildElement()
@@ -1986,7 +1987,7 @@
                 formatArgs['success'] = self.success
             else:
                 formatArgs['success'] = self.failure
-            print (self.format % formatArgs).encode('utf-8')
+            print((self.format % formatArgs).encode('utf-8'))
 
 
     def report(self, output):

Modified: CalendarServer/trunk/contrib/performance/loadtest/population.py
===================================================================
--- CalendarServer/trunk/contrib/performance/loadtest/population.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/loadtest/population.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # limitations under the License.
 #
 ##
+from __future__ import print_function
 
 """
 Tools for generating a population of CalendarServer users based on
@@ -336,10 +337,10 @@
     def eventReceived(self, event):
         self._times.append(event['duration'])
         if len(self._times) == 200:
-            print 'mean:', mean(self._times)
-            print 'median:', median(self._times)
-            print 'stddev:', stddev(self._times)
-            print 'mad:', mad(self._times)
+            print('mean:', mean(self._times))
+            print('median:', median(self._times))
+            print('stddev:', stddev(self._times))
+            print('mad:', mad(self._times))
             del self._times[:100]
 
 

Modified: CalendarServer/trunk/contrib/performance/loadtest/sim.py
===================================================================
--- CalendarServer/trunk/contrib/performance/loadtest/sim.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/loadtest/sim.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # limitations under the License.
 #
 ##
+from __future__ import print_function
 
 from collections import namedtuple
 from os import environ, mkdir
@@ -261,8 +262,8 @@
                         try:
                             mkdir(serializationPath)
                         except OSError:
-                            print "Unable to create client data serialization directory: %s" % (serializationPath)
-                            print "Please consult the clientDataSerialization stanza of contrib/performance/loadtest/config.plist"
+                            print("Unable to create client data serialization directory: %s" % (serializationPath))
+                            print("Please consult the clientDataSerialization stanza of contrib/performance/loadtest/config.plist")
                             raise
 
             if 'arrival' in config:

Modified: CalendarServer/trunk/contrib/performance/massupload.py
===================================================================
--- CalendarServer/trunk/contrib/performance/massupload.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/massupload.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys, pickle
 
@@ -41,7 +42,7 @@
     try:
         options.parseOptions(sys.argv[1:])
     except UsageError, e:
-        print e
+        print(e)
         return 1
 
     fname = options['filename']

Modified: CalendarServer/trunk/contrib/performance/report.py
===================================================================
--- CalendarServer/trunk/contrib/performance/report.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/report.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys, pickle
 
@@ -20,14 +21,14 @@
 
 def main():
     if len(sys.argv) < 5:
-        print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],)
+        print('Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],))
     else:
         stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5])
         if len(sys.argv) == 5:
-            print 'Samples'
-            print '\t' + '\n\t'.join(map(str, stat.squash(samples)))
-            print 'Commands'
-            print '\t' + '\n\t'.join(stat.commands)
+            print('Samples')
+            print('\t' + '\n\t'.join(map(str, stat.squash(samples))))
+            print('Commands')
+            print('\t' + '\n\t'.join(stat.commands))
         else:
-            print getattr(stat, sys.argv[5])(samples, *sys.argv[6:])
+            print(getattr(stat, sys.argv[5])(samples, *sys.argv[6:]))
 

Modified: CalendarServer/trunk/contrib/performance/sqlusage/sqlusage.py
===================================================================
--- CalendarServer/trunk/contrib/performance/sqlusage/sqlusage.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/sqlusage/sqlusage.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from StringIO import StringIO
 from caldavclientlibrary.client.clientsession import CalDAVSession
@@ -127,11 +128,11 @@
         
         # Now loop over sets of events
         for count in counts:
-            print "Testing count = %d" % (count,)
+            print("Testing count = %d" % (count,))
             self.ensureEvents(sessions[0], sessions[0].calendarHref, count)
             result = {}
             for request in requests:
-                print "  Test = %s" % (request.label,)
+                print("  Test = %s" % (request.label,))
                 result[request.label] = request.execute()
             self.results[count] = result
     
@@ -144,7 +145,7 @@
     def _printReport(self, title, attr, colFormat):
         table = tables.Table()
         
-        print title
+        print(title)
         headers = ["Events"] + self.requestLabels
         table.addHeader(headers)
         formats = [tables.Table.ColumnFormat("%d", tables.Table.ColumnFormat.RIGHT_JUSTIFY)] + \
@@ -155,8 +156,8 @@
             table.addRow(row)
         os = StringIO()
         table.printTable(os=os)
-        print os.getvalue()
-        print
+        print(os.getvalue())
+        print("")
             
     def ensureEvents(self, session, calendarhref, n):
         """
@@ -175,9 +176,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: sqlusage.py [options] [FILE]
+    print("""Usage: sqlusage.py [options] [FILE]
 Options:
     -h             Print this help and exit
     --server       Server hostname
@@ -191,7 +192,7 @@
 
 Description:
 This utility will analyze the output of s pg_stat_statement table.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)

Modified: CalendarServer/trunk/contrib/performance/sqlwatch.py
===================================================================
--- CalendarServer/trunk/contrib/performance/sqlwatch.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/sqlwatch.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys, signal, time
 
@@ -52,20 +53,20 @@
     while True:
         pids = instancePIDs(directory)
         dtrace = DTraceCollector("sql_measure.d", pids)
-        print 'Starting'
+        print('Starting')
         yield dtrace.start()
-        print 'Started'
+        print('Started')
         try:
             yield waitForInterrupt()
         except Stop:
             yield dtrace.stop()
             break
-        print 'Stopping'
+        print('Stopping')
         stats = yield dtrace.stop()
         for s in stats:
             if s.name == 'execute':
                 s.statements(stats[s])
-        print 'Stopped'
+        print('Stopped')
 
 
 def main():

Modified: CalendarServer/trunk/contrib/performance/stats.py
===================================================================
--- CalendarServer/trunk/contrib/performance/stats.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/stats.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import random, time
 
@@ -190,10 +191,10 @@
         if byTime:
             header = '%10s %10s %10s %s'
             row = '%10.5f %10.5f %10d %s'
-            print header % ('TOTAL MS', 'PERCALL MS', 'NCALLS', 'STATEMENT')
+            print(header % ('TOTAL MS', 'PERCALL MS', 'NCALLS', 'STATEMENT'))
             for (time, count, statement) in byTime:
                 time = time / NANO * 1000
-                print row % (time, time / count, count, statement)
+                print(row % (time, time / count, count, statement))
 
 
     def transcript(self, samples):
@@ -470,8 +471,8 @@
     
     total = 0
     for k, v in sorted(result.items(), key=lambda x:x[0]):
-        print "%d\t%.5f" % (k, float(v)/result[1])
+        print("%d\t%.5f" % (k, float(v)/result[1]))
         total += k * v
         
-    print "Average: %.2f" % (float(total) / sum(result.values()),)
+    print("Average: %.2f" % (float(total) / sum(result.values()),))
 

Modified: CalendarServer/trunk/contrib/performance/upload.py
===================================================================
--- CalendarServer/trunk/contrib/performance/upload.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/performance/upload.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys
 import pickle
@@ -71,13 +72,13 @@
         'max': str(max_value),
         'min': str(min_value),
         }
-    print 'uploading', data
+    print('uploading', data)
     agent = Agent(reactor)
     d = agent.request('POST', url, None, StringProducer(urlencode(data)))
     def check(response):
         d = readBody(response)
         def read(body):
-            print 'body', repr(body)
+            print('body', repr(body))
             if response.code != 200:
                 raise Exception("Upload failed: %r" % (response.code,))
         d.addCallback(read)
@@ -110,7 +111,7 @@
     try:
         options.parseOptions(sys.argv[1:])
     except UsageError, e:
-        print e
+        print(e)
         return 1
 
     fname, benchmark, param, statistic = options['statistic'].split(',')

Modified: CalendarServer/trunk/contrib/tools/anonymous_log.py
===================================================================
--- CalendarServer/trunk/contrib/tools/anonymous_log.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/anonymous_log.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from gzip import GzipFile
 import getopt
@@ -47,10 +48,10 @@
                 
                 if not line.startswith("Log"):
                     line = self.anonymizeLine(line)
-                print line,
+                print(line, end="")
         
         except Exception, e:
-            print "Exception: %s for %s" % (e, line,)
+            print("Exception: %s for %s" % (e, line,))
             raise
 
     def anonymizeLine(self, line):
@@ -108,9 +109,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: anonymous_log [options] [FILE]
+    print("""Usage: anonymous_log [options] [FILE]
 Options:
     -h            Print this help and exit
 
@@ -120,7 +121,7 @@
 Description:
     This utility will anonymize the content of an access log.
 
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -153,11 +154,11 @@
             if arg.endswith("/"):
                 arg = arg[:-1]
             if not os.path.exists(arg):
-                print "Path does not exist: '%s'. Ignoring." % (arg,)
+                print("Path does not exist: '%s'. Ignoring." % (arg,))
                 continue
 
             CalendarServerLogAnalyzer().anonymizeLogFile(arg)
 
     except Exception, e:
         sys.exit(str(e))
-        print traceback.print_exc()
+        print(traceback.print_exc())

Modified: CalendarServer/trunk/contrib/tools/dtraceanalyze.py
===================================================================
--- CalendarServer/trunk/contrib/tools/dtraceanalyze.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/dtraceanalyze.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -16,8 +16,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+from __future__ import with_statement
 
-from __future__ import with_statement
 import collections
 import getopt
 import os
@@ -55,7 +56,7 @@
             
             re_matched = re.match("(..) ([^ ]+) \(([^\)]+)\)", line)
             if re_matched is None:
-                print line
+                print(line)
             results = re_matched.groups()
             if results[0] == "<-":
                 self.entering = False
@@ -175,7 +176,7 @@
                             backstack.pop()
                         if backstack: backstack.pop()
                         if indent < 0:
-                            print "help"
+                            print("help")
                     current_line = current_line.parent if current_line else None
                 min_indent = min(min_indent, indent)
 
@@ -229,7 +230,7 @@
 
     def analyze(self, do_stack, no_collapse):
         
-        print "Parsing dtrace output."
+        print("Parsing dtrace output.")
         
         # Parse the trace lines first and look for the start of the call times
         lines = []
@@ -254,22 +255,22 @@
         self.printTraceDetails(lines, do_stack, no_collapse)
         
         for ctr, title in enumerate(("Sorted by Count", "Sorted by Exclusive", "Sorted by Inclusive",)):
-            print title
+            print(title)
             self.printCallTimeTotals(ctr)
 
     def printTraceDetails(self, lines, do_stack, no_collapse):
 
-        print "Found %d lines" % (len(lines),)
-        print "============================"
-        print ""
+        print("Found %d lines" % (len(lines),))
+        print("============================")
+        print("")
         
         self.stack = Dtrace.DtraceStack(lines, no_collapse)
         if do_stack:
             with file("stacked.txt", "w") as f:
                 self.stack.prettyPrint(f)
-            print "Wrote stack calls to 'stacked.txt'"
-            print "============================"
-            print ""
+            print("Wrote stack calls to 'stacked.txt'")
+            print("============================")
+            print("")
 
         # Get stats for each call
         stats = {}
@@ -285,17 +286,17 @@
             else:
                 last_exit = line.getPartialKey()
         
-        print "Function Call Counts"
-        print ""
+        print("Function Call Counts")
+        print("")
         table = tables.Table()
         table.addHeader(("Count", "Function", "File",))
         for key, value in sorted(stats.iteritems(), key=lambda x: x[1][0], reverse=True):
             table.addRow(("%d (%d)" % value, key[1], key[0],))
         table.printTable()
 
-        print ""
-        print "Called By Counts"
-        print ""
+        print("")
+        print("Called By Counts")
+        print("")
         table = tables.Table()
         table.addHeader(("Function", "Caller", "Count",))
         for main_key in sorted(self.stack.called_by.keys(), key=lambda x: x[1] + x[0]):
@@ -309,9 +310,9 @@
                 first = False
         table.printTable()
 
-        print ""
-        print "Call Into Counts"
-        print ""
+        print("")
+        print("Call Into Counts")
+        print("")
         table = tables.Table()
         table.addHeader(("Function", "Calls", "Count",))
         for main_key in sorted(self.stack.call_into.keys(), key=lambda x: x[1] + x[0]):
@@ -324,7 +325,7 @@
                 ))
                 first = False
         table.printTable()
-        print ""
+        print("")
 
     def parseCallTimeLine(self, line, index):
     
@@ -370,13 +371,13 @@
         ))
     
         table.printTable()
-        print ""
+        print("")
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: dtraceanalyze [options] FILE
+    print("""Usage: dtraceanalyze [options] FILE
 Options:
     -h          Print this help and exit
     --stack     Save indented stack to file
@@ -396,7 +397,7 @@
     > sudo ./trace.d PID > results.txt
     ...
     > ./dtraceanalyze.py results.txt
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -432,17 +433,17 @@
         if not os.path.exists(filepath):
             usage("File '%s' does not exist" % (filepath,))
             
-        print "CalendarServer dtrace analysis tool tool"
-        print "====================================="
-        print ""
+        print("CalendarServer dtrace analysis tool tool")
+        print("=====================================")
+        print("")
         if do_stack:
-            print "Generating nested stack call file."
+            print("Generating nested stack call file.")
         if no_collapse:
-            print "Consecutive function calls will not be removed."
+            print("Consecutive function calls will not be removed.")
         else:
-            print "Consecutive function calls will be removed."
-        print "============================"
-        print ""
+            print("Consecutive function calls will be removed.")
+        print("============================")
+        print("")
     
         Dtrace(filepath).analyze(do_stack, no_collapse)
 

Modified: CalendarServer/trunk/contrib/tools/fakecalendardata.py
===================================================================
--- CalendarServer/trunk/contrib/tools/fakecalendardata.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/fakecalendardata.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import datetime
 import getopt
@@ -116,9 +117,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: fakecalendardata [options]
+    print("""Usage: fakecalendardata [options]
 Options:
     -h          Print this help and exit
     -a          Percentage of events that should include attendees
@@ -133,7 +134,7 @@
 Description:
 This utility will generate fake iCalendar data either into a single .ics
 file or into multiple .ics files.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -206,7 +207,7 @@
 
     vevents = []
     for count, (recurring, attendees, date, hour) in enumerate(eventTypes):
-        #print recurring, attendees, date, hour
+        #print(recurring, attendees, date, hour)
         vevents.append(makeVEVENT(recurring, attendees, date, hour, count+1))
 
-    print calendar_template % {"VEVENTS" : "".join(vevents)}
+    print(calendar_template % {"VEVENTS" : "".join(vevents)})

Modified: CalendarServer/trunk/contrib/tools/harpoon.py
===================================================================
--- CalendarServer/trunk/contrib/tools/harpoon.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/harpoon.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 # Sends SIGTERM to any calendar server child process whose VSIZE exceeds 2GB
 # Only for use in a specific environment
@@ -54,9 +55,9 @@
                 continue
             serverProcessCount += 1
             if vsize > CUTOFFBYTES:
-                print "Killing process %d with VSIZE %d" % (pidNumber, vsize)
+                print("Killing process %d with VSIZE %d" % (pidNumber, vsize))
                 os.kill(pidNumber, signal.SIGTERM)
                 numKilled += 1
 
-print "Examined %d server processes" % (serverProcessCount,)
-print "Killed %d processes" % (numKilled,)
+print("Examined %d server processes" % (serverProcessCount,))
+print("Killed %d processes" % (numKilled,))

Modified: CalendarServer/trunk/contrib/tools/monitoranalysis.py
===================================================================
--- CalendarServer/trunk/contrib/tools/monitoranalysis.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/monitoranalysis.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import matplotlib.pyplot as plt
 import getopt
@@ -26,7 +27,7 @@
 
 def analyze(fpath, noweekends, startDate=None, endDate=None, title=None):
     
-    print "Analyzing data for %s" % (fpath,)
+    print("Analyzing data for %s" % (fpath,))
     data = []
     firstDate = None
     global initialDate
@@ -77,7 +78,7 @@
     
                     if reqs <= 80:
                         data.append((dtstamp, reqs, resp, lqnon, cpu))
-                    #print "%s %d %d %d %d" % (dtstamp, reqs, resp, lqnon, cpu)
+                    #print("%s %d %d %d %d" % (dtstamp, reqs, resp, lqnon, cpu))
             except StopIteration:
                 break
     
@@ -93,7 +94,7 @@
 
     dataset.append((title, data,))
     
-    print "Stored %d data points" % (len(data),)
+    print("Stored %d data points" % (len(data),))
 
 def plotListenQBands(data, first, last, xlim, ylim):
 
@@ -161,7 +162,7 @@
 
 def plot(figure, noshow, nosave, pngDir, xlim, ylim):
     
-    print "Plotting data"
+    print("Plotting data")
     
     plt.figure(figure, figsize=(16, 5 * len(dataset)))
 
@@ -193,9 +194,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: monitoranalysis [options] [FILE+]
+    print("""Usage: monitoranalysis [options] [FILE+]
 Options:
     -h             Print this help and exit
     -d             Directory to save PNGs to
@@ -216,7 +217,7 @@
 Description:
 This utility will analyze the output of the request monitor tool and
 generate some pretty plots of data.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -273,7 +274,7 @@
         count = 1
         for name in fnames:
             if name.startswith("request.log"):
-                print "Found file: %s" % (os.path.join(scanDir, name),)
+                print("Found file: %s" % (os.path.join(scanDir, name),))
                 trailer = name[len("request.log"):]
                 if trailer.startswith("."):
                     trailer = trailer[1:]

Modified: CalendarServer/trunk/contrib/tools/monitorsplit.py
===================================================================
--- CalendarServer/trunk/contrib/tools/monitorsplit.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/monitorsplit.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import getopt
 import sys
@@ -29,7 +30,7 @@
     
     global outputFile, fileCount, lastWeek
 
-    print "Splitting data for %s" % (fpath,)
+    print("Splitting data for %s" % (fpath,))
     f = GzipFile(fpath) if fpath.endswith(".gz") else open(fpath)
     for line in f:
         if line.startswith("2010/0"):
@@ -48,7 +49,7 @@
                 outputFile = open(os.path.join(outputDir, "request.log.%s" % (date,)), "w")
                 fileCount += 1
                 lastWeek = currentWeek
-                print "Changed to week of %s" % (date,)
+                print("Changed to week of %s" % (date,))
         
             output = ["-----\n"]
             output.append(line)
@@ -75,9 +76,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: monitoranalysis [options] FILE+
+    print("""Usage: monitoranalysis [options] FILE+
 Options:
     -h          Print this help and exit
     -d          Directory to store split files in
@@ -92,7 +93,7 @@
 Description:
 This utility will analyze the output of the request monitor tool and
 generate some pretty plots of data.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -125,4 +126,4 @@
     for arg in args:
         split(argPath(arg), outputDir)
     
-    print "Created %d files" % (fileCount,)
+    print("Created %d files" % (fileCount,))

Modified: CalendarServer/trunk/contrib/tools/netstatus.py
===================================================================
--- CalendarServer/trunk/contrib/tools/netstatus.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/netstatus.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Tool to monitor network connection status and track queue sizes and
@@ -80,20 +81,20 @@
             else:
                 pendingq[key] = (timestamp, recv, sendq,)
 
-        print "------------------------"
-        print ""
-        print time.asctime()
-        print "State        Total    RecvQ    SendQ"
+        print("------------------------")
+        print("")
+        print(time.asctime())
+        print("State        Total    RecvQ    SendQ")
         for ctr, items in enumerate(stateNames):
-            print "%11s  %5d    %5d    %5d" % (items[0], states[ctr][0], states[ctr][1], states[ctr][2])
+            print("%11s  %5d    %5d    %5d" % (items[0], states[ctr][0], states[ctr][1], states[ctr][2]))
     
-        print ""
-        print "Source IP              Established (secs)    RecvQ    SendQ"
+        print("")
+        print("Source IP              Established (secs)    RecvQ    SendQ")
         for key, value in sorted(pendingq.iteritems(), key=lambda x:x[1]):
             startedat, recv, sendq = value
             deltatime = timestamp - startedat
             if deltatime > 0:
-                print "%-20s   %3d                   %5s    %5s" % (key, deltatime, recv, sendq,)
+                print("%-20s   %3d                   %5s    %5s" % (key, deltatime, recv, sendq,))
 
         sys.stdout.flush()
         time.sleep(5)

Modified: CalendarServer/trunk/contrib/tools/pg_stats_analysis.py
===================================================================
--- CalendarServer/trunk/contrib/tools/pg_stats_analysis.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/pg_stats_analysis.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sqlparse
 import os
@@ -51,7 +52,7 @@
     try:
         statements = sqlparse.parse(sql)
     except ValueError, e:
-        print e
+        print(e)
     # Replace any literal values with placeholders
     qmark = sqlparse.sql.Token('Operator', '?')
     _substitute(statements[0], qmark)
@@ -134,9 +135,9 @@
                     None,
                 ))
 
-        print "Queries sorted by %s" % (sorttype,)
+        print("Queries sorted by %s" % (sorttype,))
         table.printTable()
-        print ""
+        print("")
  
 def parseStats(logFilePath, donormlize=True, verbose=False):
     
@@ -175,20 +176,20 @@
                 bits = [bit.strip() for bit in bits]
                 entries.append(bits)
                 if verbose and divmod(len(entries), 1000)[1] == 0:
-                    print "%d entries" % (len(entries),)
+                    print("%d entries" % (len(entries),))
                 #if float(bits[COLUMN_total_time]) > 1:
-                #    print bits[COLUMN_total_time], bits[COLUMN_query]
+                #    print(bits[COLUMN_total_time], bits[COLUMN_query])
     
     if verbose:
-        print "Read %d entries" % (len(entries,))
+        print("Read %d entries" % (len(entries,)))
     
     sqlStatementsReport(entries)
             
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: pg_stats_analysis.py [options] FILE
+    print("""Usage: pg_stats_analysis.py [options] FILE
 Options:
     -h             Print this help and exit
     -v             Generate progress information
@@ -199,7 +200,7 @@
 
 Description:
 This utility will analyze the output of s pg_stat_statement table.
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)

Modified: CalendarServer/trunk/contrib/tools/protocolanalysis.py
===================================================================
--- CalendarServer/trunk/contrib/tools/protocolanalysis.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/protocolanalysis.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from gzip import GzipFile
 import collections
@@ -319,7 +320,7 @@
                 try:
                     self.parseLine(line)
                 except:
-                    print "Could not parse line:\n%s" % (line,)
+                    print("Could not parse line:\n%s" % (line,))
                     continue
         
                 # Filter method
@@ -480,7 +481,7 @@
                 self.userInteractionAnalysis(adjustedMethod)
 
         except Exception:
-            print "Failed to process line:\n%s" % (line,)
+            print("Failed to process line:\n%s" % (line,))
             raise
     
         # Average various items
@@ -942,85 +943,85 @@
 
         self.printInfo(doTabs)
         
-        print "Load Analysis"
+        print("Load Analysis")
         self.printHourlyTotals(doTabs, summary)
         
         if not summary:
-            print "Client Analysis"
+            print("Client Analysis")
             self.printClientTotals(doTabs)
             
-            print "Protocol Analysis Count"
+            print("Protocol Analysis Count")
             self.printHourlyByXXXDetails(
                 self.hourlyByOKMethodCount if self.separate401s else self.hourlyByMethodCount,
                 doTabs,
             )
             
-            print "Protocol Analysis Average Response Time (ms)"
+            print("Protocol Analysis Average Response Time (ms)")
             self.printHourlyByXXXDetails(
                 self.averagedHourlyByOKMethodTime if self.separate401s else self.averagedHourlyByMethodTime,
                 doTabs,
                 showAverages=True,
             )
             
-            print "Protocol Analysis Total Response Time (ms)"
+            print("Protocol Analysis Total Response Time (ms)")
             self.printHourlyByXXXDetails(
                 self.hourlyByOKMethodTime if self.separate401s else self.hourlyByMethodTime,
                 doTabs,
                 showFloatPercent=True,
             )
             
-            print "Status Code Analysis"
+            print("Status Code Analysis")
             self.printHourlyByXXXDetails(self.hourlyByStatus, doTabs)
             
-            print "Protocol Analysis by Status"
+            print("Protocol Analysis by Status")
             self.printXXXMethodDetails(self.statusByMethodCount, doTabs, False)
             
-            print "Cache Analysis"
+            print("Cache Analysis")
             self.printHourlyCacheDetails(doTabs)
             
             if len(self.hourlyPropfindByResponseCount):
-                print "PROPFIND Calendar response count distribution"
+                print("PROPFIND Calendar response count distribution")
                 self.printHourlyByXXXDetails(self.hourlyPropfindByResponseCount, doTabs)
             
             if len(self.averagedHourlyByRecipientCount):
-                print "Average Recipient Counts"
+                print("Average Recipient Counts")
                 self.printHourlyByXXXDetails(self.averagedHourlyByRecipientCount, doTabs, showTotals=False)
                 
-            print "Queue Depth vs Response Time"
+            print("Queue Depth vs Response Time")
             self.printQueueDepthResponseTime(doTabs)
             
-            print "Instance Count Distribution"
+            print("Instance Count Distribution")
             self.printInstanceCount(doTabs)
     
-            print "Protocol Analysis by Client"
+            print("Protocol Analysis by Client")
             self.printXXXMethodDetails(self.clientIDByMethodCount, doTabs)
             
             if len(self.requestSizeByBucket):
-                print "Request size distribution"
+                print("Request size distribution")
                 self.printHourlyByXXXDetails(self.requestSizeByBucket, doTabs)
             
             if len(self.responseSizeByBucket):
-                print "Response size distribution (excluding GET Dropbox)"
+                print("Response size distribution (excluding GET Dropbox)")
                 self.printHourlyByXXXDetails(self.responseSizeByBucket, doTabs)
             
             if len(self.averageResponseCountByMethod):
-                print "Average response count by method"
+                print("Average response count by method")
                 self.printResponseCounts(doTabs)
             
             if len(self.requestTimeByBucket):
-                print "Response time distribution"
+                print("Response time distribution")
                 self.printHourlyByXXXDetails(self.requestTimeByBucket, doTabs)
             
-            print "URI Counts"
+            print("URI Counts")
             self.printURICounts(doTabs)
     
-            #print "User Interaction Counts"
+            #print("User Interaction Counts")
             #self.printUserInteractionCounts(doTabs)
     
-            print "User Weights (top 100)"
+            print("User Weights (top 100)")
             self.printUserWeights(doTabs)
     
-            #print "User Response times"
+            #print("User Response times")
             #self.printUserResponseTimes(doTabs)
 
     def printInfo(self, doTabs):
@@ -1037,7 +1038,7 @@
         table.addRow(("Lines Analyzed:", sum(self.linesRead.values()),))
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def getHourFromIndex(self, index):
         
@@ -1112,7 +1113,7 @@
         )
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printClientTotals(self, doTabs):
         
@@ -1145,7 +1146,7 @@
         ))
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printHourlyByXXXDetails(self, hourlyByXXX, doTabs, showTotals=True, showAverages=False, showFloatPercent=False):
     
@@ -1235,7 +1236,7 @@
             table.addFooter(row)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printHourlyCacheDetails(self, doTabs):
     
@@ -1326,7 +1327,7 @@
         table.addFooter(row)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printQueueDepthResponseTime(self, doTabs):
         
@@ -1347,7 +1348,7 @@
             ))
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printXXXMethodDetails(self, data, doTabs, verticalTotals=True):
     
@@ -1383,7 +1384,7 @@
         table.addFooter(row)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printInstanceCount(self, doTabs):
     
@@ -1412,7 +1413,7 @@
             ))
    
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printURICounts(self, doTabs):
     
@@ -1435,7 +1436,7 @@
             ))
    
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printUserWeights(self, doTabs):
     
@@ -1458,7 +1459,7 @@
             ))
    
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printResponseCounts(self, doTabs):
     
@@ -1480,7 +1481,7 @@
         table.addFooter(("Total:", self.averageResponseCountByMethod[" TOTAL"],))
    
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printUserResponseTimes(self, doTabs):
     
@@ -1508,7 +1509,7 @@
             ))
    
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
     def printUserInteractionCounts(self, doTabs):
         table = tables.Table()
@@ -1524,7 +1525,7 @@
             # Chop off the "(a):" part.
             table.addRow((k[4:], v, safePercent(float(v), total)))
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
 
 
 class TablePrinter(object):
@@ -1583,7 +1584,7 @@
             table.addFooter(row)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
                     
 class Differ(TablePrinter):
     
@@ -1595,24 +1596,24 @@
         
         self.printInfo(doTabs)
 
-        print "Load Analysis Differences"
+        print("Load Analysis Differences")
         #self.printLoadAnalysisDetails(doTabs)
         self.printHourlyTotals(doTabs)
 
         if not summary:
-            print "Client Differences"
+            print("Client Differences")
             self.printClientTotals(doTabs)
     
-            print "Protocol Count Differences"
+            print("Protocol Count Differences")
             self.printMethodCountDetails(doTabs)
     
-            print "Average Response Time Differences"
+            print("Average Response Time Differences")
             self.printMethodTimingDetails("clientByMethodAveragedTime", doTabs)
     
-            print "Total Response Time Differences"
+            print("Total Response Time Differences")
             self.printMethodTimingDetails("clientByMethodTotalTime", doTabs)
             
-            print "Average Response Count Differences"
+            print("Average Response Count Differences")
             self.printResponseCountDetails(doTabs)
 
     def printInfo(self, doTabs):
@@ -1626,7 +1627,7 @@
             table.addRow(("Filtered to user:", self.analyzers[0].filterByUser,))
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printLoadAnalysisDetails(self, doTabs):
         
@@ -1781,7 +1782,7 @@
         table.addFooter(ftr, columnFormats=fmt)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printClientTotals(self, doTabs):
         
@@ -1863,7 +1864,7 @@
         table.addFooter(footer)
     
         table.printTabDelimitedData() if doTabs else table.printTable()
-        print ""
+        print("")
     
     def printMethodCountDetails(self, doTabs):
         
@@ -1953,9 +1954,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: protocolanalysis [options] [FILE]
+    print("""Usage: protocolanalysis [options] [FILE]
 Options:
     -h            Print this help and exit
     --hours       Range of hours (local time) to analyze [0:23]
@@ -1976,7 +1977,7 @@
     tabulated statistics. It can also display statistics about the
     differences between two logs.
 
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -2053,7 +2054,7 @@
                 logs.extend(glob.iglob(arg))
             else:
                 if not os.path.exists(arg):
-                    print "Path does not exist: '%s'. Ignoring." % (arg,)
+                    print("Path does not exist: '%s'. Ignoring." % (arg,))
                     continue
                 logs.append(arg)
            
@@ -2061,7 +2062,7 @@
         for log in logs:
             if diffMode or not analyzers:
                 analyzers.append(CalendarServerLogAnalyzer(startHour, endHour, utcoffset, resolution, filterByUser, filterByClient))
-            print "Analyzing: %s" % (log,)
+            print("Analyzing: %s" % (log,))
             analyzers[-1].analyzeLogFile(log)
 
         if diffMode and len(analyzers) > 1:
@@ -2074,12 +2075,12 @@
                     again = raw_input("Repeat analysis [y/n]:")
                     if again.lower()[0] == "n":
                         break
-                    print "\n\n\n"
+                    print("\n\n\n")
                     for arg in args:
-                        print "Analyzing: %s" % (arg,)
+                        print("Analyzing: %s" % (arg,))
                         analyzers[0].analyzeLogFile(arg)
                     analyzers[0].printAll(doTabDelimited, summary)
                 
     except Exception, e:
-        print traceback.print_exc()
+        print(traceback.print_exc())
         sys.exit(str(e))

Modified: CalendarServer/trunk/contrib/tools/readStats.py
===================================================================
--- CalendarServer/trunk/contrib/tools/readStats.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/readStats.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from StringIO import StringIO
 import collections
@@ -72,23 +73,23 @@
 
 def printStat(stats, index, showMethods, topUsers, showAgents):
 
-    print "- " * 40
-    print "Server: %s" % (stats["Server"],)
-    print datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
-    print "Service Uptime: %s" % (datetime.timedelta(seconds=(int(time.time() - stats["System"]["start time"]))),)
+    print("- " * 40)
+    print("Server: %s" % (stats["Server"],))
+    print(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
+    print("Service Uptime: %s" % (datetime.timedelta(seconds=(int(time.time() - stats["System"]["start time"]))),))
     if stats["System"]["cpu count"] > 0:
-        print "Current CPU: %.1f%% (%d CPUs)" % (
+        print("Current CPU: %.1f%% (%d CPUs)" % (
             stats["System"]["cpu use"],
             stats["System"]["cpu count"],
-        )
-        print "Current Memory Used: %d bytes (%.1f GB) (%.1f%% of total)" % (
+        ))
+        print("Current Memory Used: %d bytes (%.1f GB) (%.1f%% of total)" % (
             stats["System"]["memory used"],
             stats["System"]["memory used"] / (1024.0 * 1024 * 1024),
             stats["System"]["memory percent"],
-        )
+        ))
     else:
-        print "Current CPU: Unavailable"
-        print "Current Memory Used: Unavailable"
+        print("Current CPU: Unavailable")
+        print("Current Memory Used: Unavailable")
     print
     printRequestSummary(stats)
     printHistogramSummary(stats[index], index)
@@ -105,8 +106,8 @@
 
     labels = serverLabels(stats)
 
-    print "- " * 40
-    print datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
+    print("- " * 40)
+    print(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
 
     times = []
     for stat in stats:
@@ -163,10 +164,10 @@
 
 def printFailedStats(message):
 
-    print "- " * 40
-    print datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
-    print message
-    print
+    print("- " * 40)
+    print(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
+    print(message)
+    print("")
 
 
 
@@ -209,7 +210,7 @@
 
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
@@ -274,13 +275,13 @@
 
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
 def printHistogramSummary(stat, index):
 
-    print "%s average response histogram" % (index,)
+    print("%s average response histogram" % (index,))
     table = tables.Table()
     table.addHeader(
         ("", "<10ms", "10ms<->100ms", "100ms<->1s", "1s<->10s", "10s<->30s", "30s<->60s", ">60s", "Over 1s", "Over 10s"),
@@ -314,7 +315,7 @@
         ))
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
@@ -339,7 +340,7 @@
 
 def printMethodCounts(stat):
 
-    print "Method Counts"
+    print("Method Counts")
     table = tables.Table()
     table.addHeader(
         ("Method", "Count", "%", "Av. Response", "%", "Total Resp. %"),
@@ -377,7 +378,7 @@
         ))
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
@@ -397,7 +398,7 @@
 
 def printUserCounts(stat, topUsers):
 
-    print "User Counts"
+    print("User Counts")
     table = tables.Table()
     table.addHeader(
         ("User", "Total", "Percentage"),
@@ -419,7 +420,7 @@
         ))
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
@@ -436,7 +437,7 @@
 
 def printAgentCounts(stat):
 
-    print "User-Agent Counts"
+    print("User-Agent Counts")
     table = tables.Table()
     table.addHeader(
         ("User-Agent", "Total", "Percentage"),
@@ -458,7 +459,7 @@
         ))
     os = StringIO()
     table.printTable(os=os)
-    print os.getvalue()
+    print(os.getvalue())
 
 
 
@@ -475,9 +476,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: readStats [options]
+    print("""Usage: readStats [options]
 Options:
     -h            Print this help and exit
     -s            Name of local socket to read from
@@ -495,7 +496,7 @@
     This utility will print a summary of statistics read from a
     server continuously with the specified delay.
 
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)

Modified: CalendarServer/trunk/contrib/tools/request_monitor.py
===================================================================
--- CalendarServer/trunk/contrib/tools/request_monitor.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/request_monitor.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from dateutil.parser import parse as dateparse
 from subprocess import Popen, PIPE, STDOUT
@@ -41,7 +42,7 @@
 elif output == "Linux":
     OS = "Linux"
 else:
-    print "Unknown OS: %s" % (output,)
+    print("Unknown OS: %s" % (output,))
     sys.exit(1)
 
 # Some system commands we need to detect
@@ -215,8 +216,8 @@
             return "%d bytes (%.1f GB)" % (freed, freed / (1024.0 * 1024 * 1024),)
     except Exception, e:
         if debug:
-            print "freemem failure", e
-            print traceback.print_exc()
+            print("freemem failure", e)
+            print(traceback.print_exc())
         return "error"
 
 
@@ -290,22 +291,22 @@
 
 
 def usage():
-    print "request_monitor [OPTIONS] [FILENAME]"
-    print
-    print "FILENAME   optional path of access log to monitor [/var/log/caldavd/access.log]"
-    print
-    print "OPTIONS"
-    print "-h         print help and exit"
-    print "--debug    print tracebacks and error details"
-    print "--lines N  specifies how many lines to tail from access.log (default: 10000)"
-    print "--range M:N  specifies a range of lines to analyze from access.log (default: all)"
-    print "--procs N  specifies how many python processes are expected in the log file (default: 80)"
-    print "--top N    how many long requests to print (default: 10)"
-    print "--users N  how many top users to print (default: 5)"
-    print "--router   analyze a partition server router node"
-    print "--worker   analyze a partition server worker node"
-    print
-    print "Version: 5"
+    print("request_monitor [OPTIONS] [FILENAME]")
+    print("")
+    print("FILENAME   optional path of access log to monitor [/var/log/caldavd/access.log]")
+    print("")
+    print("OPTIONS")
+    print("-h         print help and exit")
+    print("--debug    print tracebacks and error details")
+    print("--lines N  specifies how many lines to tail from access.log (default: 10000)")
+    print("--range M:N  specifies a range of lines to analyze from access.log (default: all)")
+    print("--procs N  specifies how many python processes are expected in the log file (default: 80)")
+    print("--top N    how many long requests to print (default: 10)")
+    print("--users N  how many top users to print (default: 5)")
+    print("--router   analyze a partition server router node")
+    print("--worker   analyze a partition server worker node")
+    print("")
+    print("Version: 5")
 
 numLines = 10000
 numProcs = 80
@@ -342,21 +343,21 @@
 
 for filename in filenames:
     if not os.path.isfile(filename):
-        print "Path %s does not exist" % (filename,)
-        print
+        print("Path %s does not exist" % (filename,))
+        print("")
         usage()
         sys.exit(1)
 
 for filename in filenames:
     if not os.access(filename, os.R_OK):
-        print "Path %s does not exist" % (filename,)
-        print
+        print("Path %s does not exist" % (filename,))
+        print("")
         usage()
         sys.exit(1)
 
 if debug:
-    print "Starting: access log files: %s" % (", ".join(filenames),)
-    print
+    print("Starting: access log files: %s" % (", ".join(filenames),))
+    print("")
 
 while True:
 
@@ -405,11 +406,11 @@
                     parseErrors += 1
 
                     if debug:
-                        print "Access log line parse failure", e
-                        print traceback.print_exc()
-                        print "---"
-                        print line
-                        print "---"
+                        print("Access log line parse failure", e)
+                        print(traceback.print_exc())
+                        print("---")
+                        print(line)
+                        print("---")
 
                     continue
 
@@ -491,24 +492,24 @@
 
         times.sort()
         if len(times) == 0:
-            print "No data to analyze"
+            print("No data to analyze")
             time.sleep(10)
             continue
 
         totalRequests = sum(numRequests.values())
 
-        print "- " * 40
-        print datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
+        print("- " * 40)
+        print(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),)
         if enableListenQueue:
             q, lqssl, lqnon = listenQueueHistory()
-            print "Listenq (ssl+non):", q[0], " (Recent", ", ".join(q[1:]), "Oldest)"
+            print("Listenq (ssl+non):", q[0], " (Recent", ", ".join(q[1:]), "Oldest)")
         if enableCpuIdle:
             q = idleHistory()
-            print "CPU idle %:", q[0], " (Recent", ", ".join(q[1:]), "Oldest)"
+            print("CPU idle %:", q[0], " (Recent", ", ".join(q[1:]), "Oldest)")
         if enableFreeMem:
-            print "Memory free:", freemem()
-        print "CPU Per Daemon:", cpuPerDaemon()
-        print
+            print("Memory free:", freemem())
+        print("CPU Per Daemon:", cpuPerDaemon())
+        print("")
 
         table = tables.Table()
         table.addHeader(
@@ -592,14 +593,14 @@
 
         os = StringIO()
         table.printTable(os=os)
-        print os.getvalue()
+        print(os.getvalue())
 
         if enableListenQueue:
             lqlatency = (lqssl / avgRequests, lqnon / avgRequests,) if avgRequests else (0.0, 0.0,)
-            print " listenq latency (ssl+non): %.1f s %.1f s" % (
+            print(" listenq latency (ssl+non): %.1f s %.1f s" % (
                 lqlatency[0],
                 lqlatency[1],
-            )
+            ))
 
         table = tables.Table()
         table.addHeader(
@@ -634,19 +635,19 @@
             ))
         os = StringIO()
         table.printTable(os=os)
-        print os.getvalue()
+        print(os.getvalue())
         print
         if errorCount:
-            print "Number of 500 errors: %d" % (errorCount,)
+            print("Number of 500 errors: %d" % (errorCount,))
         if parseErrors:
-            print "Number of access log parsing errors: %d" % (parseErrors,)
+            print("Number of access log parsing errors: %d" % (parseErrors,))
         if errorCount or parseErrors:
-            print
+            print("")
 
-        print "Proc:   Peak outstanding:        Seconds of processing (number of requests):"
+        print("Proc:   Peak outstanding:        Seconds of processing (number of requests):")
         for l in xrange((numProcs - 1) / 10 + 1):
             base = l * 10
-            print "%2d-%2d: " % (base, base + 9),
+            print("%2d-%2d: " % (base, base + 9),)
 
             for i in xrange(base, base + 10):
                 try:
@@ -654,9 +655,9 @@
                     s = "%1d" % (r,)
                 except KeyError:
                     s = "."
-                print s,
+                print(s, end="")
 
-            print "    ",
+            print("    ", end="")
 
             for i in xrange(base, base + 10):
                 try:
@@ -665,12 +666,12 @@
                     s = "%4.0f(%4d)" % (r, c)
                 except KeyError:
                     s = "         ."
-                print s,
+                print(s, end="")
 
-            print
+            print("")
 
-        print
-        print "Top %d longest (in most recent %d requests):" % (numTop, sum(numRequests.values()),)
+        print("")
+        print("Top %d longest (in most recent %d requests):" % (numTop, sum(numRequests.values()),))
         requests.sort()
         requests.reverse()
         for i in xrange(numTop):
@@ -683,14 +684,14 @@
                     if _logId == logId and _logTime > reqStartTime and _reqStartTime < logTime:
                         overlapCount += 1
 
-                print "%7.1fms  %-12s %s res:%.1fKB, %s [%s] #%d +%d %s->%s" % (respTime, userId, method, kb, ext, client, logId, overlapCount, reqStartTime.strftime("%H:%M:%S"), logTime.strftime("%H:%M:%S"),)
+                print("%7.1fms  %-12s %s res:%.1fKB, %s [%s] #%d +%d %s->%s" % (respTime, userId, method, kb, ext, client, logId, overlapCount, reqStartTime.strftime("%H:%M:%S"), logTime.strftime("%H:%M:%S"),))
                 """
-                print "%7.1fms  %-12s %s res:%.1fKB, %s [%s] #%d %s->%s" % (respTime, userId, method, kb, ext, client, logId, reqStartTime.strftime("%H:%M:%S"), logTime.strftime("%H:%M:%S"),)
+                print("%7.1fms  %-12s %s res:%.1fKB, %s [%s] #%d %s->%s" % (respTime, userId, method, kb, ext, client, logId, reqStartTime.strftime("%H:%M:%S"), logTime.strftime("%H:%M:%S"),))
             except:
                 pass
 
-        print
-        print "Top %d busiest users (in most recent %d requests):" % (numUsers, totalRequests,)
+        print("")
+        print("Top %d busiest users (in most recent %d requests):" % (numUsers, totalRequests,))
         userlist = []
         for user, userStat in users.iteritems():
             userlist.append((userStat['count'], user, userStat))
@@ -699,16 +700,16 @@
         for i in xrange(numUsers):
             try:
                 count, user, userStat = userlist[i]
-                print "%3d  %-12s " % (count, user),
+                print("%3d  %-12s " % (count, user), end="")
                 clientStat = userStat['clients']
                 clients = clientStat.keys()
                 if len(clients) == 1:
-                    print "[%s]" % (clients[0],)
+                    print("[%s]" % (clients[0],))
                 else:
                     clientList = []
                     for client in clients:
                         clientList.append("%s: %d" % (client, clientStat[client]))
-                    print "[%s]" % ", ".join(clientList)
+                    print("[%s]" % ", ".join(clientList))
             except:
                 pass
 
@@ -719,8 +720,8 @@
             break
 
     except Exception, e:
-        print "Script failure", e
+        print("Script failure", e)
         if debug:
-            print traceback.print_exc()
+            print(traceback.print_exc())
 
     time.sleep(10)

Modified: CalendarServer/trunk/contrib/tools/sortrecurrences.py
===================================================================
--- CalendarServer/trunk/contrib/tools/sortrecurrences.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/sortrecurrences.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import getopt
 import os
@@ -23,9 +24,9 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print """Usage: sortrecurrences FILE
+    print("""Usage: sortrecurrences FILE
 Options:
     -h            Print this help and exit
 
@@ -35,7 +36,7 @@
 Description:
     This utility will output a sorted iCalendar component.
 
-"""
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -68,13 +69,13 @@
             if arg.endswith("/"):
                 arg = arg[:-1]
             if not os.path.exists(arg):
-                print "Path does not exist: '%s'. Ignoring." % (arg,)
+                print("Path does not exist: '%s'. Ignoring." % (arg,))
                 continue
 
             cal = PyCalendar()
             cal.parse(open(arg))
-            print str(cal.serialize())
+            print(str(cal.serialize()))
 
     except Exception, e:
         sys.exit(str(e))
-        print traceback.print_exc()
+        print(traceback.print_exc())

Modified: CalendarServer/trunk/contrib/tools/sqldata_from_path.py
===================================================================
--- CalendarServer/trunk/contrib/tools/sqldata_from_path.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/contrib/tools/sqldata_from_path.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Prints out an SQL statement that can be used in an SQL shell against
@@ -27,16 +28,16 @@
 
 def usage(error_msg=None):
     if error_msg:
-        print error_msg
+        print(error_msg)
 
-    print "sqldata_from_path PATH"
-    print
-    print "PATH   filestore or HTTP path"
-    print
-    print """Prints out an SQL statement that can be used in an SQL shell against
-an sqlstore database to return the calendar or address data for the provided
-filestore or HTTP path. Path must be a __uids__ path.
-"""
+    print("sqldata_from_path PATH")
+    print("")
+    print("PATH   filestore or HTTP path")
+    print("""
+Prints out an SQL statement that can be used in an SQL shell against
+an sqlstore database to return the calendar or address data for the
+provided filestore or HTTP path. Path must be a __uids__ path.
+""")
 
     if error_msg:
         raise ValueError(error_msg)
@@ -105,11 +106,11 @@
     sqlstrings[datatype]["collection"] = collection
     sqlstrings[datatype]["resource"] = resource
 
-    print """select %(object_data)s from %(object_table)s where
+    print("""select %(object_data)s from %(object_table)s where
     %(object_name)s = '%(resource)s' and %(object_bind_id)s = (
         select %(bind_id)s from %(bind_table)s where
             %(bind_name)s = '%(collection)s' and %(bind_home_id)s = (
                 select RESOURCE_ID from %(home_table)s where OWNER_UID = '%(uid)s'
             )
-    );""" % sqlstrings[datatype]
+    );""" % sqlstrings[datatype])
     

Modified: CalendarServer/trunk/setup.py
===================================================================
--- CalendarServer/trunk/setup.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/setup.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import sys
 import os
@@ -172,7 +173,7 @@
         for script in dist.scripts:
             scriptPath = os.path.join(install_scripts, os.path.basename(script))
 
-            print "rewriting %s" % (scriptPath,)
+            print("rewriting %s" % (scriptPath,))
 
             script = []
 

Modified: CalendarServer/trunk/support/version.py
===================================================================
--- CalendarServer/trunk/support/version.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/support/version.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 from os.path import dirname, basename
@@ -75,4 +76,4 @@
 
 if __name__ == "__main__":
     base_version, comment = version()
-    print "%s (%s)" % (base_version, comment)
+    print("%s (%s)" % (base_version, comment))

Modified: CalendarServer/trunk/test
===================================================================
--- CalendarServer/trunk/test	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/test	2013-02-26 20:09:34 UTC (rev 10813)
@@ -95,11 +95,32 @@
   rm -f "${tmp}";
 fi;
 
+search_py ()
+{
+  find . \
+    ! '(' -type d '(' -path '*/.*' -or -name data ')' -prune ')' \
+    -type f -name '*.py' \
+    -print0 \
+    | xargs -0 -n 100 grep "$@";
+}
+
+#tmp="$(mktemp "/tmp/calendarserver_test_flakish.XXXXX")";
+#echo "";
+#echo "Checking for other issues..."
+#search_py 'print  *[^(]' | sed 's|#.*||' | grep 'print  *[^(]' > "${tmp}" || true;
+#if [ -s "${tmp}" ]; then
+#    echo "**** Use of legacy print statement found. ****";
+#    cat "${tmp}";
+#    exit 1;
+#fi;
+#rm -f "${tmp}";
+
 tmp="$(mktemp "/tmp/calendarserver_test_emtpy.XXXXX")";
-find "${wd}" '!' '(' -type d '(' -path '*/.*' -o -name data ')' -prune ')' -type f -size 0 > "${tmp}";
+find "${wd}" '!' '(' -type d '(' -path '*/.*' -or -name data ')' -prune ')' -type f -size 0 > "${tmp}";
 if [ -s "${tmp}" ]; then
     echo "**** Empty files: ****";
     cat "${tmp}";
     exit 1;
 fi;
 rm -f "${tmp}";
+

Modified: CalendarServer/trunk/twext/enterprise/dal/parseschema.py
===================================================================
--- CalendarServer/trunk/twext/enterprise/dal/parseschema.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/enterprise/dal/parseschema.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Parser for SQL schema.
@@ -167,7 +168,7 @@
 
             schema.tableNamed(tableName).insertSchemaRow(rowData)
         else:
-            print 'unknown type:', stmt.get_type()
+            print('unknown type:', stmt.get_type())
     return schema
 
 
@@ -438,8 +439,8 @@
                 else:
                     expected = False
                 if not expected:
-                    print 'UNEXPECTED TOKEN:', repr(val), theColumn
-                    print self.parens
+                    print('UNEXPECTED TOKEN:', repr(val), theColumn)
+                    print(self.parens)
                     import pprint
                     pprint.pprint(self.parens.tokens)
                     return 0

Modified: CalendarServer/trunk/twext/internet/gaiendpoint.py
===================================================================
--- CalendarServer/trunk/twext/internet/gaiendpoint.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/internet/gaiendpoint.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 L{getaddrinfo}()-based endpoint
@@ -164,18 +165,18 @@
     from twisted.internet.protocol import Factory, Protocol
     class HelloGoobye(Protocol, object):
         def connectionMade(self):
-            print 'Hello!'
+            print('Hello!')
             self.transport.loseConnection()
 
         def connectionLost(self, reason):
-            print 'Goodbye'
+            print('Goodbye')
 
     class MyFactory(Factory, object):
         def buildProtocol(self, addr):
-            print 'Building protocol for:', addr
+            print('Building protocol for:', addr)
             return HelloGoobye()
     def bye(what):
-        print 'bye', what
+        print('bye', what)
         reactor.stop()
     gaie.connect(MyFactory()).addBoth(bye)
     reactor.run()

Modified: CalendarServer/trunk/twext/python/_plistlib.py
===================================================================
--- CalendarServer/trunk/twext/python/_plistlib.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/python/_plistlib.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -1,6 +1,8 @@
 #
 # Added to standard library in Python 2.6 (Mac only in prior versions)
 #
+from __future__ import print_function
+
 """plistlib.py -- a tool to generate and parse MacOSX .plist files.
 
 The PropertList (.plist) file format is a simple XML pickle supporting
@@ -50,7 +52,7 @@
 Parse Plist example::
 
     pl = readPlist(pathOrFile)
-    print pl["aKey"]
+    print(pl["aKey"])
 """
 
 

Modified: CalendarServer/trunk/twext/python/log.py
===================================================================
--- CalendarServer/trunk/twext/python/log.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/python/log.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Classes and functions to do granular logging.
@@ -110,7 +111,7 @@
 #    # In case we add log levels that don't map to pythong logging levels:
 #    #
 #    for l in logLevels:
-#        print "Trying %s: %s, %s" % (l, l in pythonLogLevelMapping, cmpLogLevels(level, l) <= 0)
+#        print("Trying %s: %s, %s" % (l, l in pythonLogLevelMapping, cmpLogLevels(level, l) <= 0))
 #        if l in pythonLogLevelMapping and cmpLogLevels(level, l) <= 0:
 #            return pythonLogLevelMapping[l]
 #

Modified: CalendarServer/trunk/twext/python/memcacheclient.py
===================================================================
--- CalendarServer/trunk/twext/python/memcacheclient.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/python/memcacheclient.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+from __future__ import print_function
 
 """
 client module for memcached (memory cache daemon)
@@ -319,7 +320,7 @@
         for i in range(Client._SERVER_RETRIES):
             server = self.buckets[serverhash % len(self.buckets)]
             if server.connect():
-                #print "(using server %s)" % server,
+                #print("(using server %s)" % server, end="")
                 return server, key
             serverhash = serverHashFunction(str(serverhash) + str(i))
         log.error("Memcacheclient _get_server( ) failed to connect")
@@ -1310,9 +1311,9 @@
     return doctest.testmod(memcacheclient, globs=globs)
 
 if __name__ == "__main__":
-    print "Testing docstrings..."
+    print("Testing docstrings...")
     _doctest()
-    print "Running tests:"
+    print("Running tests:")
     print
     serverList = [["127.0.0.1:11211"]]
     if '--do-unix' in sys.argv:
@@ -1326,14 +1327,14 @@
                 return "%s (%s)" % (val, type(val))
             return "%s" % val
         def test_setget(key, val):
-            print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)),
+            print("Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)), end="")
             mc.set(key, val)
             newval = mc.get(key)
             if newval == val:
-                print "OK"
+                print("OK")
                 return 1
             else:
-                print "FAIL"
+                print("FAIL")
                 return 0
 
 
@@ -1350,107 +1351,107 @@
         test_setget("a_string", "some random string")
         test_setget("an_integer", 42)
         if test_setget("long", long(1<<30)):
-            print "Testing delete ...",
+            print("Testing delete ...", end="")
             if mc.delete("long"):
-                print "OK"
+                print("OK")
             else:
-                print "FAIL"
-        print "Testing get_multi ...",
-        print mc.get_multi(["a_string", "an_integer"])
+                print("FAIL")
+        print("Testing get_multi ...", end="")
+        print(mc.get_multi(["a_string", "an_integer"]))
 
-        print "Testing get(unknown value) ...",
-        print to_s(mc.get("unknown_value"))
+        print("Testing get(unknown value) ...", end="")
+        print(to_s(mc.get("unknown_value")))
 
         f = FooStruct()
         test_setget("foostruct", f)
 
-        print "Testing incr ...",
+        print("Testing incr ...", end="")
         x = mc.incr("an_integer", 1)
         if x == 43:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing decr ...",
+        print("Testing decr ...", end="")
         x = mc.decr("an_integer", 1)
         if x == 42:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
         # sanity tests
-        print "Testing sending spaces...",
+        print("Testing sending spaces...", end="")
         try:
             x = mc.set("this has spaces", 1)
         except Client.MemcachedKeyCharacterError, msg:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing sending control characters...",
+        print("Testing sending control characters...", end="")
         try:
             x = mc.set("this\x10has\x11control characters\x02", 1)
         except Client.MemcachedKeyCharacterError, msg:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing using insanely long key...",
+        print("Testing using insanely long key...", end="")
         try:
             x = mc.set('a'*SERVER_MAX_KEY_LENGTH + 'aaaa', 1)
         except Client.MemcachedKeyLengthError, msg:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing sending a unicode-string key...",
+        print("Testing sending a unicode-string key...", end="")
         try:
             x = mc.set(u'keyhere', 1)
         except Client.MemcachedStringEncodingError, msg:
-            print "OK",
+            print("OK", end="")
         else:
-            print "FAIL",
+            print("FAIL", end="")
         try:
             x = mc.set((u'a'*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
         except:
-            print "FAIL",
+            print("FAIL", end="")
         else:
-            print "OK",
+            print("OK", end="")
         import pickle
         s = pickle.loads('V\\u4f1a\np0\n.')
         try:
             x = mc.set((s*SERVER_MAX_KEY_LENGTH).encode('utf-8'), 1)
         except Client.MemcachedKeyLengthError:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing using a value larger than the memcached value limit...",
+        print("Testing using a value larger than the memcached value limit...", end="")
         x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH)
         if mc.get('keyhere') == None:
-            print "OK",
+            print("OK", end="")
         else:
-            print "FAIL",
+            print("FAIL", end="")
         x = mc.set('keyhere', 'a'*SERVER_MAX_VALUE_LENGTH + 'aaa')
         if mc.get('keyhere') == None:
-            print "OK"
+            print("OK")
         else:
-            print "FAIL"
+            print("FAIL")
 
-        print "Testing set_multi() with no memcacheds running",
+        print("Testing set_multi() with no memcacheds running", end="")
         mc.disconnect_all()
         errors = mc.set_multi({'keyhere' : 'a', 'keythere' : 'b'})
         if errors != []:
-            print "FAIL"
+            print("FAIL")
         else:
-            print "OK"
+            print("OK")
 
-        print "Testing delete_multi() with no memcacheds running",
+        print("Testing delete_multi() with no memcacheds running", end="")
         mc.disconnect_all()
         ret = mc.delete_multi({'keyhere' : 'a', 'keythere' : 'b'})
         if ret != 1:
-            print "FAIL"
+            print("FAIL")
         else:
-          print "OK"
+          print("OK")
 
 # vim: ts=4 sw=4 et :

Modified: CalendarServer/trunk/twext/web2/dav/resource.py
===================================================================
--- CalendarServer/trunk/twext/web2/dav/resource.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/web2/dav/resource.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -22,6 +22,7 @@
 #
 # DRI: Wilfredo Sanchez, wsanchez at apple.com
 ##
+from __future__ import print_function
 
 """
 WebDAV resources.
@@ -759,7 +760,7 @@
             )[2].append((resource, url))
 
         # Now determine whether each ace satisfies privileges
-        #print aclmap
+        #print(aclmap)
         for items in aclmap.itervalues():
             checked = (yield self.checkACLPrivilege(
                 request, items[0], items[1], privileges, inherited_aces

Modified: CalendarServer/trunk/twext/web2/fileupload.py
===================================================================
--- CalendarServer/trunk/twext/web2/fileupload.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/web2/fileupload.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -21,7 +21,7 @@
 # SOFTWARE.
 #
 ##
-from __future__ import generators
+from __future__ import print_function
 
 import re
 from zope.interface import implements
@@ -74,7 +74,7 @@
             line = defer.waitForDeferred(line)
             yield line
             line = line.getResult()
-        #print "GOT", line
+        #print("GOT", line)
         if not line.endswith('\r\n'):
             if line == "":
                 raise MimeFormatError("Unexpected end of stream.")
@@ -194,7 +194,7 @@
         return d
 
     def _readFirstBoundary(self):
-        #print "_readFirstBoundary"
+        #print("_readFirstBoundary")
         line = self.stream.readline(size=1024)
         if isinstance(line, defer.Deferred):
             line = defer.waitForDeferred(line)
@@ -209,7 +209,7 @@
     _readFirstBoundary = defer.deferredGenerator(_readFirstBoundary)
 
     def _readBoundaryLine(self):
-        #print "_readBoundaryLine"
+        #print("_readBoundaryLine")
         line = self.stream.readline(size=1024)
         if isinstance(line, defer.Deferred):
             line = defer.waitForDeferred(line)
@@ -227,7 +227,7 @@
     _readBoundaryLine = defer.deferredGenerator(_readBoundaryLine)
 
     def _doReadHeaders(self, morefields):
-        #print "_doReadHeaders", morefields
+        #print("_doReadHeaders", morefields)
         if not morefields:
             return None
         return _readHeaders(self.stream)
@@ -392,7 +392,7 @@
     log = Logger()
     d.addErrback(log.err)
     def pr(s):
-        print s
+        print(s)
     d.addCallback(pr)
 
 

Modified: CalendarServer/trunk/twext/web2/http_headers.py
===================================================================
--- CalendarServer/trunk/twext/web2/http_headers.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/web2/http_headers.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -1,5 +1,5 @@
 # -*- test-case-name: twext.web2.test.test_http_headers -*-
-# #
+##
 # Copyright (c) 2008 Twisted Matrix Laboratories.
 # Copyright (c) 2010-2013 Apple Computer, Inc. All rights reserved.
 #
@@ -21,7 +21,8 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 # SOFTWARE.
 #
-# #
+##
+from __future__ import print_function
 
 """
 HTTP header representation, parsing, and serialization.
@@ -100,7 +101,7 @@
 
         try:
             for p in parser:
-                # print "Parsing %s: %s(%s)" % (name, repr(p), repr(h))
+                # print("Parsing %s: %s(%s)" % (name, repr(p), repr(h)))
                 header = p(header)
                 # if isinstance(h, types.GeneratorType):
                 #     h=list(h)
@@ -125,7 +126,7 @@
         generator = self.HTTPGenerators.get(name, None)
 
         if generator is None:
-            # print self.generators
+            # print(self.generators)
             raise ValueError("No header generator for header '%s', either add one or use setHeaderRaw." % (name,))
 
         for g in generator:

Modified: CalendarServer/trunk/twext/web2/server.py
===================================================================
--- CalendarServer/trunk/twext/web2/server.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/web2/server.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -22,6 +22,7 @@
 # SOFTWARE.
 #
 ##
+from __future__ import print_function
 
 """
 This is a web-server which integrates with the twisted.internet
@@ -297,7 +298,7 @@
         else:
             self.prepath = []
             self.postpath = path
-        #print "_parseURL", self.uri, (self.uri, self.scheme, self.host, self.path, self.params, self.querystring)
+        #print("_parseURL", self.uri, (self.uri, self.scheme, self.host, self.path, self.params, self.querystring))
 
     def _schemeFromPort(self, port):
         """

Modified: CalendarServer/trunk/twext/web2/test/test_client.py
===================================================================
--- CalendarServer/trunk/twext/web2/test/test_client.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twext/web2/test/test_client.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -1,5 +1,6 @@
 # Copyright (c) 2001-2007 Twisted Matrix Laboratories.
 # See LICENSE for details.
+from __future__ import print_function
 
 """
 Tests for HTTP client.
@@ -393,7 +394,7 @@
         req = http.ClientRequest('GET', '/', None, None)
 
         def gotResp(r):
-            print r
+            print(r)
 
         d = cxn.client.submitRequest(req).addCallback(gotResp)
 

Modified: CalendarServer/trunk/twistedcaldav/backup.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/backup.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/backup.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Utility code for backup and restore
@@ -42,12 +43,12 @@
 
 def debug(string):
     if VERBOSE:
-        print "DEBUG:", string
+        print("DEBUG:", string)
 
 
 def funclog(string):
     if FUNCLOG:
-        print "FUNCLOG:", string
+        print("FUNCLOG:", string)
 
 
 def logFuncCall(func):

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_guidchange.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_guidchange.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_guidchange.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+
 from twistedcaldav.directory.directory import DirectoryService
 
 from txdav.xml import element as davxml
@@ -93,14 +95,14 @@
             if allowed:
                 def onError(f):
                     f.trap(AccessDeniedError)
-                    #print resource.readDeadProperty(davxml.ACL).toxml()
+                    #print(resource.readDeadProperty(davxml.ACL).toxml())
                     self.fail("%s should have %s privilege on %r" % (principal, privilege.sname(), resource))
                 d.addErrback(onError)
             else:
                 def onError(f):
                     f.trap(AccessDeniedError)
                 def onSuccess(_):
-                    #print resource.readDeadProperty(davxml.ACL).toxml()
+                    #print(resource.readDeadProperty(davxml.ACL).toxml())
                     self.fail("%s should not have %s privilege on %r" % (principal, privilege.sname(), resource))
                 d.addCallback(onSuccess)
                 d.addErrback(onError)

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_ldapdirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_ldapdirectory.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_ldapdirectory.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 try:
     from twistedcaldav.directory.ldapdirectory import (
@@ -29,7 +30,7 @@
     from string import maketrans
     import ldap
 except ImportError:
-    print "Skipping because ldap module not installed"
+    print("Skipping because ldap module not installed")
 else:
     from twistedcaldav.test.util import TestCase
 

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_livedirectory.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_livedirectory.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_livedirectory.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 runLDAPTests = False
 runODTests = False
@@ -33,7 +34,7 @@
         pass # Don't run live tests
 
 except ImportError:
-    print "Could not import ldap module (skipping LDAP tests)"
+    print("Could not import ldap module (skipping LDAP tests)")
 
 try:
     from calendarserver.platform.darwin.od import opendirectory, dsattributes
@@ -54,10 +55,10 @@
     if "odtestamanda" in recordNames:
         runODTests = True
     else:
-        print "Test OD records not found (skipping OD tests)"
+        print("Test OD records not found (skipping OD tests)")
 
 except ImportError:
-    print "Could not import OpenDirectory framework (skipping OD tests)"
+    print("Could not import OpenDirectory framework (skipping OD tests)")
 
 
 if runLDAPTests or runODTests:
@@ -144,7 +145,7 @@
     if runLDAPTests:
 
         from twistedcaldav.directory.ldapdirectory import LdapDirectoryService
-        print "Running live LDAP tests against %s" % (testServer,)
+        print("Running live LDAP tests against %s" % (testServer,))
 
         class LiveLDAPDirectoryServiceCase(LiveDirectoryTests, TestCase):
 
@@ -181,7 +182,7 @@
     if runODTests:
 
         from twistedcaldav.directory.appleopendirectory import OpenDirectoryService
-        print "Running live OD tests"
+        print("Running live OD tests")
 
         class LiveODDirectoryServiceCase(LiveDirectoryTests, TestCase):
 

Modified: CalendarServer/trunk/twistedcaldav/directory/test/test_principal.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/directory/test/test_principal.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/directory/test/test_principal.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 import os
 
@@ -94,7 +95,7 @@
         DirectoryPrincipalResource.principalURL(),
         """
         for directory in self.directoryServices:
-            #print "\n -> %s" % (directory.__class__.__name__,)
+            #print("\n -> %s" % (directory.__class__.__name__,))
             provisioningResource = self.principalRootResources[directory.__class__.__name__]
 
             provisioningURL = "/" + directory.__class__.__name__ + "/"
@@ -107,7 +108,7 @@
             self.assertEquals(recordTypes, set(directory.recordTypes()))
 
             for recordType in recordTypes:
-                #print "   -> %s" % (recordType,)
+                #print("   -> %s" % (recordType,))
                 typeResource = provisioningResource.getChild(recordType)
                 self.failUnless(isinstance(typeResource, DirectoryPrincipalTypeProvisioningResource))
 
@@ -126,7 +127,7 @@
                 self.assertEquals(shortNames, set(expected))
 
                 for shortName in shortNames:
-                    #print "     -> %s" % (shortName,)
+                    #print("     -> %s" % (shortName,))
                     recordResource = typeResource.getChild(shortName)
                     self.failUnless(isinstance(recordResource, DirectoryPrincipalResource))
 
@@ -627,14 +628,14 @@
         Default access controls for principal provisioning resources.
         """
         for directory in self.directoryServices:
-            #print "\n -> %s" % (directory.__class__.__name__,)
+            #print("\n -> %s" % (directory.__class__.__name__,))
             provisioningResource = self.principalRootResources[directory.__class__.__name__]
 
             for args in _authReadOnlyPrivileges(self, provisioningResource, provisioningResource.principalCollectionURL()):
                 yield self._checkPrivileges(*args)
 
             for recordType in (yield provisioningResource.listChildren()):
-                #print "   -> %s" % (recordType,)
+                #print("   -> %s" % (recordType,))
                 typeResource = provisioningResource.getChild(recordType)
 
                 for args in _authReadOnlyPrivileges(self, typeResource, typeResource.principalCollectionURL()):
@@ -703,14 +704,14 @@
             if allowed:
                 def onError(f):
                     f.trap(AccessDeniedError)
-                    #print resource.readDeadProperty(davxml.ACL)
+                    #print(resource.readDeadProperty(davxml.ACL))
                     self.fail("%s should have %s privilege on %r" % (principal.sname(), privilege.sname(), resource))
                 d.addErrback(onError)
             else:
                 def expectAccessDenied(f):
                     f.trap(AccessDeniedError)
                 def onSuccess(_):
-                    #print resource.readDeadProperty(davxml.ACL)
+                    #print(resource.readDeadProperty(davxml.ACL))
                     self.fail("%s should not have %s privilege on %r" % (principal.sname(), privilege.sname(), resource))
                 d.addCallbacks(onSuccess, expectAccessDenied)
             return d

Modified: CalendarServer/trunk/twistedcaldav/extensions.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/extensions.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/extensions.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 Extensions to web2.dav
@@ -502,7 +503,7 @@
             else:
                 mimeType = child.contentType()
                 if mimeType is None:
-                    print 'BAD contentType() IMPLEMENTATION', child
+                    print('BAD contentType() IMPLEMENTATION', child)
                     contentType = 'application/octet-stream'
                 else:
                     contentType = "%s/%s" % (mimeType.mediaType, mimeType.mediaSubtype)

Modified: CalendarServer/trunk/twistedcaldav/localization.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/localization.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/localization.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,8 +13,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+from __future__ import with_statement
 
-from __future__ import with_statement
 import gettext
 import inspect
 import os
@@ -46,8 +47,8 @@
     from localization import translationTo
 
     with translationTo('de'):
-        print _("Hello")
-        print _("The event will last %(days)d days") % { 'days' : 4 }
+        print(_("Hello"))
+        print(_("The event will last %(days)d days") % { 'days' : 4 })
 
     ... Hallo
     ... Die Veranstaltung dauert 4 Tage
@@ -74,12 +75,12 @@
 nesting of "with" contexts, as in:
 
     with translationTo('de'):
-        print _("Hello") # in German
+        print(_("Hello") # in German)
 
         with translationTo('fr'):
-            print _("Hello") # in French
+            print(_("Hello") # in French)
 
-        print _("Hello") # in German
+        print(_("Hello") # in German)
 
 If a translation file cannot be found for the specified language, it will fall
 back to 'en'.  If 'en' can't be found, gettext will raise IOError.
@@ -88,12 +89,12 @@
 helper methods for date formatting:
 
     with translationTo('en') as trans:
-        print trans.dtDate(PyCalendarDateTime.getToday())
+        print(trans.dtDate(PyCalendarDateTime.getToday()))
 
     ... Thursday, October 23, 2008
 
     with translationTo('fr') as trans:
-        print trans.dtDate(PyCalendarDateTime.getToday())
+        print(trans.dtDate(PyCalendarDateTime.getToday()))
 
     ... Jeudi, Octobre 23, 2008
 

Modified: CalendarServer/trunk/twistedcaldav/query/expression.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/query/expression.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/query/expression.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,10 +13,13 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
-Query Expression Elements. These are used to build a 'generic' query expression tree that can then
-be used by different query language generators to produce the actual query syntax required (SQL, xpath eyc).
+Query Expression Elements. These are used to build a 'generic' query
+expression tree that can then be used by different query language
+generators to produce the actual query syntax required (SQL, xpath
+eyc).
 """
 
 __version__ = "0.0"
@@ -329,9 +332,9 @@
     e3 = containsExpression("summary", "help", True)
     e4 = notExpression(e3)
     e5 = andExpression([e1, e2, e4])
-    print e5
+    print(e5)
     e6 = inExpression("type", ("vevent", "vtodo",), False)
-    print e6
+    print(e6)
     e7 = notinExpression("type", ("vevent", "vtodo",), False)
-    print e7
+    print(e7)
 

Modified: CalendarServer/trunk/twistedcaldav/query/sqlgenerator.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/query/sqlgenerator.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/query/sqlgenerator.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 """
 SQL statement generator from query expressions.
@@ -320,14 +321,14 @@
     e2 = expression.timerangeExpression("20060101T120000Z", "20060101T130000Z", "20060101T080000Z", "20060101T090000Z")
     e3 = expression.notcontainsExpression("SUMMARY", "help", True)
     e5 = expression.andExpression([e1, e2, e3])
-    print e5
+    print(e5)
     sql = sqlgenerator(e5, 'dummy-cal', 'dummy-user')
-    print sql.generate()
+    print(sql.generate())
     e6 = expression.inExpression("TYPE", ("VEVENT", "VTODO",), False)
-    print e6
+    print(e6)
     sql = sqlgenerator(e6, 'dummy-cal', 'dummy-user')
-    print sql.generate()
+    print(sql.generate())
     e7 = expression.notinExpression("TYPE", ("VEVENT", "VTODO",), False)
-    print e7
+    print(e7)
     sql = sqlgenerator(e7, 'dummy-cal', 'dummy-user')
-    print sql.generate()
+    print(sql.generate())

Modified: CalendarServer/trunk/twistedcaldav/scheduling/imip/test/test_outbound.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/scheduling/imip/test/test_outbound.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/scheduling/imip/test/test_outbound.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from cStringIO import StringIO
 import os
@@ -102,7 +103,7 @@
         self.store.queuer.callWithNewProposals(self._proposalCallback)
 
     def _proposalCallback(self, wp):
-        # print "New proposal", wp
+        # print("New proposal", wp)
         self.wp = wp
 
     @inlineCallbacks

Modified: CalendarServer/trunk/twistedcaldav/scheduling/test/test_itip.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/scheduling/test/test_itip.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/scheduling/test/test_itip.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,6 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
 from pycalendar.datetime import PyCalendarDateTime
 from pycalendar.timezone import PyCalendarTimezone
@@ -867,9 +868,9 @@
             reply_success, reply_processed = iTipProcessing.processReply(itipmsg, calendar)
 #            if not description.startswith("#3.1"):
 #                continue
-#            print description
-#            print str(calendar)
-#            print str(result)
+#            print(description)
+#            print(str(calendar))
+#            print(str(result))
             self.assertEqual(
                 str(calendar).replace("\r", "").replace("\n ", ""),
                 str(result).replace("\n ", ""),

Modified: CalendarServer/trunk/twistedcaldav/test/util.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/test/util.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/twistedcaldav/test/util.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -13,7 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
-
+from __future__ import print_function
 from __future__ import with_statement
 
 import os
@@ -340,7 +340,7 @@
                     if childStructure.has_key("@optional"):
                         return True
                     else:
-                        print "Missing:", childPath
+                        print("Missing:", childPath)
                         return False
 
                 if childStructure.has_key("@contents"):
@@ -354,15 +354,15 @@
                             contents = child.read()
                             for term in expectedContents:
                                 if term not in contents:
-                                    print "Contents mismatch:", childPath
-                                    print "Expecting match:\n%s\n\nActual:\n%s\n" % (term, contents)
+                                    print("Contents mismatch:", childPath)
+                                    print("Expecting match:\n%s\n\nActual:\n%s\n" % (term, contents))
                                     return False
                     else:
                         with open(childPath) as child:
                             contents = child.read()
                             if contents != childStructure["@contents"]:
-                                print "Contents mismatch:", childPath
-                                print "Expected:\n%s\n\nActual:\n%s\n" % (childStructure["@contents"], contents)
+                                print("Contents mismatch:", childPath)
+                                print("Expected:\n%s\n\nActual:\n%s\n" % (childStructure["@contents"], contents))
                                 return False
 
                 else:
@@ -382,8 +382,8 @@
                         for attr, value in xattrs.iteritems():
                             if isinstance(value, str):
                                 if xattr.getxattr(childPath, attr) != value:
-                                    print "Xattr mismatch:", childPath, attr
-                                    print (xattr.getxattr(childPath, attr), " != ", value)
+                                    print("Xattr mismatch:", childPath, attr)
+                                    print((xattr.getxattr(childPath, attr), " != ", value))
                                     return False
                             else: # method
                                 if not value(xattr.getxattr(childPath, attr)):
@@ -398,7 +398,7 @@
 
             if actual:
                 # There are unexpected children
-                print "Unexpected:", actual, 'in', parent
+                print("Unexpected:", actual, 'in', parent)
                 return False
 
             return True

Modified: CalendarServer/trunk/txdav/base/datastore/file.py
===================================================================
--- CalendarServer/trunk/txdav/base/datastore/file.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/txdav/base/datastore/file.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,24 +14,25 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
 
-
 """
 Common utility functions for a file based datastore.
 """
 
+from zope.interface.declarations import implements
+
+from twisted.python import hashlib
+
 from twext.python.log import LoggingMixIn
 from twext.enterprise.ienterprise import AlreadyFinishedError
+from twext.web2.dav.resource import TwistedGETContentMD5
 from txdav.idav import IDataStoreObject
 from txdav.base.propertystore.base import PropertyName
+from txdav.xml.element import GETContentType
 
-from txdav.xml.rfc2518 import GETContentType
-from twext.web2.dav.resource import TwistedGETContentMD5
 
-from twisted.python import hashlib
 
-from zope.interface.declarations import implements
-
 def isValidName(name):
     """
     Determine if the given string is a valid name.  i.e. does it conflict with
@@ -102,12 +103,12 @@
 
     def __del__(self):
         if not self.done and self.info:
-            print '**** UNCOMMITTED TRANSACTION (%s) BEING GARBAGE COLLECTED ****' % (
+            print("**** UNCOMMITTED TRANSACTION (%s) BEING GARBAGE COLLECTED ****") % (
                 self.name,
             )
             for info in self.info:
-                print '   ', info
-            print '---- END OF OPERATIONS'
+                print("   "), info
+            print("---- END OF OPERATIONS")
 
 
 

Modified: CalendarServer/trunk/txdav/common/datastore/test/util.py
===================================================================
--- CalendarServer/trunk/txdav/common/datastore/test/util.py	2013-02-26 20:00:36 UTC (rev 10812)
+++ CalendarServer/trunk/txdav/common/datastore/test/util.py	2013-02-26 20:09:34 UTC (rev 10813)
@@ -14,6 +14,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from __future__ import print_function
+
 """
 Store test utility functions
 """
@@ -71,10 +73,10 @@
     between tests.  (It is currently not invoked anywhere, but may be useful if
     these types of bugs crop up in the future.)
     """
-    print '+++ ALL CONNECTIONS +++'
+    print("+++ ALL CONNECTIONS +++")
     for connection in allInstancesOf(DiagnosticConnectionWrapper):
-        print connection.label, connection.state
-    print '--- CONNECTIONS END ---'
+        print(connection.label, connection.state)
+    print("--- CONNECTIONS END ---")
 
 
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20130226/fdf684c5/attachment-0001.html>


More information about the calendarserver-changes mailing list