__name __ ==“ __ main__”函数调用出现问题

时间:2018-08-01 22:31:01

标签: python python-3.x python-2.7 subprocess

我正在努力使用python程序将所有打印调用的输出重定向到文件并通过电子邮件发送。下面是我的程序。除了电子邮件中的OUTFILE变为空白(也许文件在尝试通过电子邮件发送时仍处于打开状态)之外,其他所有功能都正常。由于我对顺序不太困惑,并且想在文件关闭后调用send_status_report()定义的内容,因此我该如何使其工作。

#! /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()

1 个答案:

答案 0 :(得分:0)

  

由于我对序列有点困惑,并且想在关闭文件后调用send_status_report()定义,所以我如何使其工作。

您有一个with open…:。块完成后,该语句将自动关闭文件。因此,如果您想在文件关闭后立即执行某项操作,只需将其放在该语句之后即可:

with open(LOG+OUTFILE, 'wb') as log_file:
    def read(fd):
    # ...
    rc = pty.spawn(argv, read)

send_status_report()

只要您现有的代码正常工作(例如,文件在完成处理之前就没有关闭),并且没有做过多次关闭文件这样的真正奇怪的事情,这将称为{{ 1}}在文件关闭之后。