我有两个独立运行的python脚本。一个将一些数据记录到日志文件,另一个将电子邮件发送到指定的电子邮件地址。我需要将这两个脚本结合在一起,以便电子邮件以指定的时间间隔发送日志文件。
我设法使两个脚本都可以单独运行,但是不确定如何将它们组合成一个工作脚本。
脚本1
def get_titles():
current_title = None
while True:
moment2 = datetime.datetime.now().strftime("%d-%b-%Y [ %H:%M:%S ]")
new_title = GetWindowText(GetForegroundWindow())
if new_title != current_title:
if len(new_title) > 0:
#logging.info(" Moved to : " + new_title)
current_title = new_title
time.sleep(0.1)
#print(new_title)
ff= (moment2 + " : " + "Moved T0 : "+ new_title + '\n')
#print (ff)
with open('logfile.txt', 'a+') as f:
f.write(ff)
脚本2
body = "Please see attatched file for info"
msg.attach(MIMEText(body, 'plain'))
filename = "logfile.txt"
attachment = open("logfile.txt", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)
msg.attach(part)
server = smtplib.SMTP('smtpname', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
答案 0 :(得分:0)
创建2个类,然后调用适当的方法?下面是一个粗略的模板。
class LogData:
def __init__():
print("Initilized!")
def get_titles():
#write to log file
...
...
...
return log_file_name
class SendEmail:
def __init__(data_file):
self.data_file = data_file
def send_email():
#read self.data_file and send email
...
...
...
if __name__ == '__main__':
log = LogData()
log_file = log.get_titles()
email_handler = SendEmail(log_file)
email_handler.send_email()