title: Issue with the __name__=="__main__" function calling
body: <p>I'm struggling with a python program to redirect the output of all print calls to a file and email it. Below is my program. Everything works fine except the <code>OUTFILE</code> in the email coming up empty (perhaps the file is still open while it tries to email it). As I'm little confused about the sequence and want to call the <code>send_status_report()</code> defined after the file is closed, how do I make it work.</p>
  
  <pre><code>#! /usr/bin/python
  import subprocess
  import os
  import pty
  import sys
  import smtplib
  import time
  from email.mime.text import MIMEText
  from email.mime.multipart import MIMEMultipart
  from email.mime.application import MIMEApplication
  
  
  def current_time():
      from datetime import datetime
      return datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
  
  
  BIN="/home/netsys/filerscripts/MANU-TEST/storage-automations/REDBUTTON-DR/"
  LOG=BIN+"Logs/"
  YMD=current_time()
  OUTFILE="ResyncLog_"+YMD+".txt"
  SMTP_SERVER="xxxxxxxx.xxx.com"
  
  #define to Call the reverse resync and output the log to both file and screen
  
  
  def send_status_report():
      dir_path = LOG
      files = [OUTFILE, "CLUSTERDEL.LOG", "RESYNC.LOG","UPDATE.LOG"]
  
      msg = MIMEMultipart()
      msg['To'] = "abc@abc.com"
      msg['From'] = "abc@abc.com"
      msg['Subject'] = "Netapp RB Automation:Reverse Resync Status"
  
      body = MIMEText('Test results attached.', 'html', 'utf-8')  
      msg.attach(body)  # add message body (text or html)
  
      for f in files:  # add files to the message
          file_path = os.path.join(dir_path, f)
          attachment = MIMEApplication(open(file_path, "rb").read(), _subtype="txt")
          attachment.add_header('Content-Disposition','attachment', filename=f)
          msg.attach(attachment)
  
      s = smtplib.SMTP()
      s.connect(host=SMTP_SERVER)
      s.sendmail(msg['From'], msg['To'], msg.as_string())
      print 'done!'
      s.close()
  
  
  def main():
      subprocess.call(BIN+"ReverseSync.py", shell=True)
  
  
  
  if __name__=="__main__":
      sentinel_option = '--dont-spawn'
      if sentinel_option not in sys.argv:
          # run itself copying output to the log file
          with open(LOG+OUTFILE, 'wb') as log_file:
              def read(fd):
                  data = os.read(fd, 1024)
                  log_file.write(data)
                  #OUTDATA = OUTDATA + data
                  return data
  
              argv = [sys.executable] + sys.argv + [sentinel_option]
              rc = pty.spawn(argv, read)
  
      else:
          sys.argv.remove(sentinel_option)
          rc = main()
      sys.exit(rc)
  
  send_status_report()
  </code></pre>