[28885] in Source-Commits

home help back first fref pref prev next nref lref last post

delete commit: Convert to python3

daemon@ATHENA.MIT.EDU (Benjamin Kaduk)
Sat Aug 22 22:36:37 2020

Date: Sat, 22 Aug 2020 22:36:32 -0400
From: Benjamin Kaduk <kaduk@mit.edu>
Message-ID: <202008230236.07N2aWOM019433@drugstore.mit.edu>
To: <source-commits@mit.edu>
MIME-Version: 1.0
Content-Type: text/plain

https://github.com/mit-athena/delete/commit/8ff8bed65d86b6301596312eefee899f1bbc786a
commit 8ff8bed65d86b6301596312eefee899f1bbc786a
Author: Miriam Rittenberg <mrittenb@mit.edu>
Date:   Wed Aug 12 09:54:08 2020 -0400

    Convert to python3

 delete       |   13 +++++++------
 expunge      |   20 +++++++++++---------
 libdelete.py |    3 ++-
 lsdel        |    9 +++++----
 undelete     |   16 +++++++++-------
 5 files changed, 34 insertions(+), 27 deletions(-)

diff --git a/delete b/delete
index 58cb9c6..861d186 100755
--- a/delete
+++ b/delete
@@ -1,9 +1,10 @@
 #!/usr/bin/python
-
+from __future__ import print_function
 import logging
 import optparse
 import os
 import shutil
+import six
 import stat
 import sys
 
@@ -37,7 +38,7 @@ def ask(question, *args, **kwargs):
     yes = ('y', 'yes')
     prepend = '' if kwargs.get('nowhoami', False) else "{0}: ".format(whoami)
     try:
-        return raw_input("%s%s " % (prepend,
+        return six.moves.input("%s%s " % (prepend,
                                     question % args)).strip().lower() in yes
     except KeyboardInterrupt:
         sys.exit(0)
@@ -51,7 +52,7 @@ def perror(message, **kwargs):
     msg = "{0}: {1}".format(whoami, message.format(**kwargs))
     logger.debug("Error: %s", msg)
     if should_print:
-        print >>sys.stderr, msg
+        print(msg, file=sys.stderr)
 
 def actually_delete(filename, options):
     """
@@ -67,7 +68,7 @@ def actually_delete(filename, options):
                    filename):
             return False
     if options.noop:
-        print >>sys.stderr, "{0}: {1} would be removed".format(whoami, filename)
+        print("{0}: {1} would be removed".format(whoami, filename), file=sys.stderr)
         return True
     (dirname, basename) = os.path.split(filename)
     newname = os.path.join(dirname, '.#' + basename)
@@ -112,7 +113,7 @@ def delete(filename, options):
                 is_empty = libdelete.empty_directory(filename)
             except OSError as e:
                 # Do we want to only do this if emulating rm?
-                print >>sys.stderr, ": ".join((whoami, e.filename, e.strerror))
+                print(": ".join((whoami, e.filename, e.strerror)), file=sys.stderr)
                 return False
             if is_empty:
                 return actually_delete(filename, options)
@@ -181,7 +182,7 @@ def main():
     for filename in args:
         # Because you know _someone_ will try it
         if len(filename.rstrip('/')) < 1:
-            print >>sys.stderr, "That's not a good idea."
+            print("That's not a good idea.", file=sys.stderr)
             sys.exit(1)
         # Trailing slashes make bad things happen
         if not delete(filename.rstrip('/'), options):
diff --git a/expunge b/expunge
index 1e9e6b9..432f617 100755
--- a/expunge
+++ b/expunge
@@ -1,8 +1,10 @@
 #!/usr/bin/python
 
+from __future__ import print_function
 import logging
 import optparse
 import os
+import six
 import sys
 
 import libdelete
@@ -40,7 +42,7 @@ def ask(question, *args, **kwargs):
     yes = ('y', 'yes')
     prepend = '' if kwargs.get('nowhoami', False) else "{0}: ".format(whoami)
     try:
-        return raw_input("%s%s " % (prepend,
+        return six.moves.input("%s%s " % (prepend,
                                     question % args)).strip().lower() in yes
     except KeyboardInterrupt:
         sys.exit(0)
@@ -54,7 +56,7 @@ def perror(message, **kwargs):
     msg = "{0}: {1}".format(whoami, message.format(**kwargs))
     logger.debug("Error: %s", msg)
     if should_print:
-        print >>sys.stderr, msg
+        print(msg, file=sys.stderr)
 
 def getsize(path):
     size = os.path.getsize(path)
@@ -64,11 +66,11 @@ def expunge(deleted_files, options):
     expunged_size = 0
     errors = 0
     if options.listfiles:
-        print header
-        print libdelete.format_columns(sorted(
+        print(header)
+        print(libdelete.format_columns(sorted(
                 [libdelete.relpath(
-                        libdelete.undeleted_name(x)) for x in deleted_files]))
-        print footer
+                        libdelete.undeleted_name(x)) for x in deleted_files])))
+        print(footer)
         if not options.force and \
                 not ask(confirmation, nowhoami=True):
             logger.debug("User failed to confirm; exiting")
@@ -97,7 +99,7 @@ def expunge(deleted_files, options):
                     # We exit here, not keep going, as the original code did
                     sys.exit(errors)
             if options.verbose:
-                print "{whoami}: {path} {size} {maybe}expunged ({total}KB total)".format(whoami=whoami, path=f, size=size_str, maybe='would be ' if options.noop else '', total=libdelete.to_kb(expunged_size))
+                print("{whoami}: {path} {size} {maybe}expunged ({total}KB total)".format(whoami=whoami, path=f, size=size_str, maybe='would be ' if options.noop else '', total=libdelete.to_kb(expunged_size)))
         if not options.noop:
             if os.path.isdir(f) and not os.path.islink(f):
                 logger.debug("rmdir: %s", f)
@@ -107,7 +109,7 @@ def expunge(deleted_files, options):
                 os.unlink(f)
 
     if options.yieldsize:
-        print "Total expunged: {0}KB".format(libdelete.to_kb(expunged_size))
+        print("Total expunged: {0}KB".format(libdelete.to_kb(expunged_size)))
     return errors
 
 def parse_options():
@@ -157,7 +159,7 @@ def main():
         if (len(sys.argv) == 2) and (sys.argv[1] == '--debug'):
             sys.argv.append('all')
         else:
-            print >>sys.stderr, "purge does not take any arguments or options."
+            print("purge does not take any arguments or options.", file=sys.stderr)
             sys.exit(1)
     (options, args) = parse_options()
     if (whoami == "purge"):
diff --git a/libdelete.py b/libdelete.py
index 932fc98..39d9b28 100644
--- a/libdelete.py
+++ b/libdelete.py
@@ -8,6 +8,7 @@ import glob
 import logging
 import os
 import re
+import six
 import sys
 import stat
 
@@ -30,7 +31,7 @@ def chunks(seq, size):
     """
     Break a sequence up into size chunks
     """
-    return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
+    return (seq[pos:pos + size] for pos in six.moves.range(0, len(seq), size))
 
 def format_columns(items, singlecol=False, width=80):
     """
diff --git a/lsdel b/lsdel
index 2d0a9de..f9226ae 100755
--- a/lsdel
+++ b/lsdel
@@ -1,5 +1,6 @@
 #!/usr/bin/python
 
+from __future__ import print_function
 import logging
 import optparse
 import os
@@ -34,7 +35,7 @@ def perror(message, **kwargs):
     msg = "{0}: {1}".format(whoami, message.format(**kwargs))
     logger.debug("Error: %s", msg)
     if should_print:
-        print >>sys.stderr, msg
+        print(msg, file=sys.stderr)
 
 def parse_options():
     parser = optparse.OptionParser(usage="%prog [options] filename ...")
@@ -93,10 +94,10 @@ def main():
             perror(e.message)
             rv = 1
 
-    print libdelete.format_columns(sorted(
+    print(libdelete.format_columns(sorted(
             [libdelete.relpath(
                     libdelete.undeleted_name(x)) for x in deleted_files]),
-                                   options.singlecolumn)
+                                   options.singlecolumn))
     if options.yieldsize:
         total = None
         try:
@@ -109,7 +110,7 @@ def main():
         if total is None:
             perror('Unable to display total size: errors occurred during calculation.')
         else:
-            print "\nTotal space taken up by files: %dKB" % round((float(total) / 1024))
+            print("\nTotal space taken up by files: %dKB" % round((float(total) / 1024)))
     return rv
 
 if __name__ == "__main__":
diff --git a/undelete b/undelete
index e3ba7ac..70dfdd1 100755
--- a/undelete
+++ b/undelete
@@ -1,9 +1,11 @@
 #!/usr/bin/python
 
+from __future__ import print_function
 import logging
 import optparse
 import os
 import shutil
+import six
 import stat
 import sys
 
@@ -35,7 +37,7 @@ def ask(question, *args, **kwargs):
     yes = ('y', 'yes')
     prepend = '' if kwargs.get('nowhoami', False) else "{0}: ".format(whoami)
     try:
-        return raw_input("%s%s " % (prepend,
+        return six.moves.input("%s%s " % (prepend,
                                     question % args)).strip().lower() in yes
     except KeyboardInterrupt:
         sys.exit(0)
@@ -49,7 +51,7 @@ def perror(message, **kwargs):
     msg = "{0}: {1}".format(whoami, message.format(**kwargs))
     logger.debug("Error: %s", msg)
     if should_print:
-        print >>sys.stderr, msg
+        print(msg, file=sys.stderr)
 
 def actually_undelete(filename, options):
     undeleted_name = libdelete.undeleted_name(filename)
@@ -69,10 +71,10 @@ def actually_undelete(filename, options):
         else:
             os.unlink(undeleted_name)
     if options.noop:
-        print >>sys.stderr, "{0}: {1} would be undeleted".format(whoami, filename)
+        print("{0}: {1} would be undeleted".format(whoami, filename), file=sys.stderr)
         return True
     os.rename(filename, undeleted_name)
-    print >>sys.stderr, "{0}: {1} undeleted".format(whoami, filename)
+    print("{0}: {1} undeleted".format(whoami, filename), file=sys.stderr)
     return True
 
 def undelete(filename, options):
@@ -101,11 +103,11 @@ def undelete(filename, options):
 def get_filenames_from_stdin(options):
     errors = 0
     if options.verbose:
-        print "Enter the files to be undeleted, one file per line."
-        print "Hit <RETURN> on a line by itself to exit.\n"
+        print("Enter the files to be undeleted, one file per line.")
+        print("Hit <RETURN> on a line by itself to exit.\n")
     while True:
         try:
-            filename = raw_input("{0}: ".format(whoami))
+            filename = six.moves.input("{0}: ".format(whoami))
         except (EOFError, KeyboardInterrupt):
             sys.exit(errors)
         if len(filename) == 0:

home help back first fref pref prev next nref lref last post