[Python-checkins] cpython: Issue #18972: Modernize email examples and use the argparse module in them.

serhiy.storchaka python-checkins at python.org
Sun Oct 6 10:45:50 CEST 2013


http://hg.python.org/cpython/rev/1b1b1d4b28e8
changeset:   86025:1b1b1d4b28e8
parent:      86023:ab7b5ba360e9
user:        Serhiy Storchaka <storchaka at gmail.com>
date:        Sun Oct 06 11:45:25 2013 +0300
summary:
  Issue #18972: Modernize email examples and use the argparse module in them.

files:
  Doc/includes/email-dir.py    |  86 ++++++++++-------------
  Doc/includes/email-unpack.py |  47 ++++--------
  Misc/NEWS                    |   5 +
  3 files changed, 57 insertions(+), 81 deletions(-)


diff --git a/Doc/includes/email-dir.py b/Doc/includes/email-dir.py
--- a/Doc/includes/email-dir.py
+++ b/Doc/includes/email-dir.py
@@ -8,7 +8,7 @@
 # For guessing MIME type based on file name extension
 import mimetypes
 
-from optparse import OptionParser
+from argparse import ArgumentParser
 
 from email import encoders
 from email.message import Message
@@ -22,44 +22,36 @@
 
 
 def main():
-    parser = OptionParser(usage="""\
+    parser = ArgumentParser(description="""\
 Send the contents of a directory as a MIME message.
-
-Usage: %prog [options]
-
 Unless the -o option is given, the email is sent by forwarding to your local
 SMTP server, which then does the normal delivery process.  Your local machine
 must be running an SMTP server.
 """)
-    parser.add_option('-d', '--directory',
-                      type='string', action='store',
-                      help="""Mail the contents of the specified directory,
-                      otherwise use the current directory.  Only the regular
-                      files in the directory are sent, and we don't recurse to
-                      subdirectories.""")
-    parser.add_option('-o', '--output',
-                      type='string', action='store', metavar='FILE',
-                      help="""Print the composed message to FILE instead of
-                      sending the message to the SMTP server.""")
-    parser.add_option('-s', '--sender',
-                      type='string', action='store', metavar='SENDER',
-                      help='The value of the From: header (required)')
-    parser.add_option('-r', '--recipient',
-                      type='string', action='append', metavar='RECIPIENT',
-                      default=[], dest='recipients',
-                      help='A To: header value (at least one required)')
-    opts, args = parser.parse_args()
-    if not opts.sender or not opts.recipients:
-        parser.print_help()
-        sys.exit(1)
-    directory = opts.directory
+    parser.add_argument('-d', '--directory',
+                        help="""Mail the contents of the specified directory,
+                        otherwise use the current directory.  Only the regular
+                        files in the directory are sent, and we don't recurse to
+                        subdirectories.""")
+    parser.add_argument('-o', '--output',
+                        metavar='FILE',
+                        help="""Print the composed message to FILE instead of
+                        sending the message to the SMTP server.""")
+    parser.add_argument('-s', '--sender', required=True,
+                        help='The value of the From: header (required)')
+    parser.add_argument('-r', '--recipient', required=True,
+                        action='append', metavar='RECIPIENT',
+                        default=[], dest='recipients',
+                        help='A To: header value (at least one required)')
+    args = parser.parse_args()
+    directory = args.directory
     if not directory:
         directory = '.'
     # Create the enclosing (outer) message
     outer = MIMEMultipart()
     outer['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)
-    outer['To'] = COMMASPACE.join(opts.recipients)
-    outer['From'] = opts.sender
+    outer['To'] = COMMASPACE.join(args.recipients)
+    outer['From'] = args.sender
     outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
 
     for filename in os.listdir(directory):
@@ -76,23 +68,19 @@
             ctype = 'application/octet-stream'
         maintype, subtype = ctype.split('/', 1)
         if maintype == 'text':
-            fp = open(path)
-            # Note: we should handle calculating the charset
-            msg = MIMEText(fp.read(), _subtype=subtype)
-            fp.close()
+            with open(path) as fp:
+                # Note: we should handle calculating the charset
+                msg = MIMEText(fp.read(), _subtype=subtype)
         elif maintype == 'image':
-            fp = open(path, 'rb')
-            msg = MIMEImage(fp.read(), _subtype=subtype)
-            fp.close()
+            with open(path, 'rb') as fp:
+                msg = MIMEImage(fp.read(), _subtype=subtype)
         elif maintype == 'audio':
-            fp = open(path, 'rb')
-            msg = MIMEAudio(fp.read(), _subtype=subtype)
-            fp.close()
+            with open(path, 'rb') as fp:
+                msg = MIMEAudio(fp.read(), _subtype=subtype)
         else:
-            fp = open(path, 'rb')
-            msg = MIMEBase(maintype, subtype)
-            msg.set_payload(fp.read())
-            fp.close()
+            with open(path, 'rb') as fp:
+                msg = MIMEBase(maintype, subtype)
+                msg.set_payload(fp.read())
             # Encode the payload using Base64
             encoders.encode_base64(msg)
         # Set the filename parameter
@@ -100,14 +88,12 @@
         outer.attach(msg)
     # Now send or store the message
     composed = outer.as_string()
-    if opts.output:
-        fp = open(opts.output, 'w')
-        fp.write(composed)
-        fp.close()
+    if args.output:
+        with open(args.output, 'w') as fp:
+            fp.write(composed)
     else:
-        s = smtplib.SMTP('localhost')
-        s.sendmail(opts.sender, opts.recipients, composed)
-        s.quit()
+        with smtplib.SMTP('localhost') as s:
+            s.sendmail(args.sender, args.recipients, composed)
 
 
 if __name__ == '__main__':
diff --git a/Doc/includes/email-unpack.py b/Doc/includes/email-unpack.py
--- a/Doc/includes/email-unpack.py
+++ b/Doc/includes/email-unpack.py
@@ -8,41 +8,27 @@
 import errno
 import mimetypes
 
-from optparse import OptionParser
+from argparse import ArgumentParser
 
 
 def main():
-    parser = OptionParser(usage="""\
+    parser = ArgumentParser(description="""\
 Unpack a MIME message into a directory of files.
+""")
+    parser.add_argument('-d', '--directory', required=True,
+                        help="""Unpack the MIME message into the named
+                        directory, which will be created if it doesn't already
+                        exist.""")
+    parser.add_argument('msgfile')
+    args = parser.parse_args()
 
-Usage: %prog [options] msgfile
-""")
-    parser.add_option('-d', '--directory',
-                      type='string', action='store',
-                      help="""Unpack the MIME message into the named
-                      directory, which will be created if it doesn't already
-                      exist.""")
-    opts, args = parser.parse_args()
-    if not opts.directory:
-        parser.print_help()
-        sys.exit(1)
+    with open(args.msgfile) as fp:
+        msg = email.message_from_file(fp)
 
     try:
-        msgfile = args[0]
-    except IndexError:
-        parser.print_help()
-        sys.exit(1)
-
-    try:
-        os.mkdir(opts.directory)
-    except OSError as e:
-        # Ignore directory exists error
-        if e.errno != errno.EEXIST:
-            raise
-
-    fp = open(msgfile)
-    msg = email.message_from_file(fp)
-    fp.close()
+        os.mkdir(args.directory)
+    except FileExistsError:
+        pass
 
     counter = 1
     for part in msg.walk():
@@ -59,9 +45,8 @@
                 ext = '.bin'
             filename = 'part-%03d%s' % (counter, ext)
         counter += 1
-        fp = open(os.path.join(opts.directory, filename), 'wb')
-        fp.write(part.get_payload(decode=True))
-        fp.close()
+        with open(os.path.join(args.directory, filename), 'wb') as fp:
+            fp.write(part.get_payload(decode=True))
 
 
 if __name__ == '__main__':
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -60,6 +60,11 @@
 - Issue #4366: Fix building extensions on all platforms when --enable-shared
   is used.
 
+Documentation
+-------------
+
+- Issue #18972: Modernize email examples and use the argparse module in them.
+
 Build
 -----
 

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list