def NetDown(SwitchIP, compRoom): num = 0 flag = 0 for i in range(5): NetStatus = CheckNet(SwitchIP) if not NetStatus: num = num + 1 time.sleep(2) if num == 5: mylogger.info("###########5 connect fail,going to down #############") do(compRoom, flag) return True else: mylogger.info( "###########5 connect success,going to mail #############") SendMail(compRoom)
def run(day_format): #day format like 2017-10-23 year, month, day= day_format.split("-") domains = get_domain() for domain in domains: base_dir = "/usr/local/nginx/html/hdfs/download/" hdfs_path = domain + "/" + year + "/" + month + "/" + day local_path = base_dir + hdfs_path if is_path_exist(local_path): all_files = get_recursive_file_list(local_path) for file_path in all_files: local_size = get_file_size(file_path) hour = file_path.split("/")[-1] domain_path = "/"+domain day_path = "./" + day_format ftp_path = "/"+domain + "/" + day_format + "/" + day_format+"_"+hour ftp_size, cmds = push_file_ftp(file_path, domain_path, day_path, ftp_path) if ftp_size=="0": toollogger.error(traceback.format_exc()) SendMail().send_mail(day_format, cmds) else: toollogger.info( ftp_path + "\t" + str(local_size) + "\t" + ftp_size + "\t" +str(int(local_size) - int(ftp_size)))
def sendBookInfo(self): '''将预约成功信息发送到邮箱''' seat_name = self.book_result['data']['list']['spaceInfo']['name'] book_time = self.book_result['data']['list']['beginTime']['date'] deadline = time.mktime(time.strptime(book_time, '%Y-%m-%d %H:%M:%S')) + 1800 deadline = time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime(deadline)) # 格式化成 2020-09-16 19:45:33 形式 mail = SendMail() mail.smtp_server = self.stu.smtp_server mail.username = self.stu.from_email mail.password = self.stu.from_pw mail.to_email = self.stu.to_email mail.subject = f'已成功预约 {seat_name} 号座位' mail.message = (f'已成功为您预约了位于三楼平层北区的 {seat_name} 号座位~\n\n' f'预约开始时间: {book_time}\n' f'请务必于 {deadline} 之前抵达图书馆并签到\n\n' '“While there\'s life, there\'s hope.”\n' ' ― Marcus Tullius Cicero\n') mail.send()
debug_logger = getLogger("debug") result_logger = getLogger("result") debug_fh = FileHandler(debug_logfilename, "a+") result_fh = FileHandler(result_logfilename, "a+") debug_logger.addHandler(debug_fh) result_logger.addHandler(result_fh) debug_logger.setLevel(DEBUG) result_logger.setLevel(DEBUG) if __name__ == '__main__': args = sys.argv sendmail = SendMail("*****@*****.**", "*****@*****.**", property_path) # コマンドライン引数から、通貨とモード取得 instrument = args[1] mode = args[2] algo = args[3] config_name = args[4] base_time = datetime.now() if len(args) > 5: test_args = args[5] else: test_args = "live" if test_args == "test": end_time = datetime.strptime("2019-05-25 00:00:00", "%Y-%m-%d %H:%M:%S")
trade_account, trade_obj["instrument"], trade_obj["side"], units, 0, 0) #print(response) else: #print(trade_obj) pass if trade_obj["flag"]: trade_obj = stl(insert_time, trade_obj, profit_rate, orderstop_rate) print(trade_obj) if trade_obj["stl_flag"]: debug_logger.info( "========================================") for key in trade_obj: debug_logger.info("%s=%s" % (key, trade_obj[key])) trade_obj = reset_tradeobj() if mode != "test": # if 1 == 1: response = oanda_wrapper.close_position( trade_account) #print(response) except: message = traceback.format_exc() debug_logger.info(message) sendmail = SendMail("*****@*****.**", "*****@*****.**", "../property") sendmail.set_msg(message) sendmail.send_mail()
from netcup_crawler import NetcupCrawler from send_mail import SendMail crawler = NetcupCrawler() mail = SendMail() entries = crawler.fetch() if crawler.check(entries): crawler.save(entries) subject = "Netcup - Neues Sonderangebot" body = "" for entry in entries: body += "<br>Angebot: " + entry.title + "<br> Preis: " + entry.price + "<br>" recepients = {"*****@*****.**", "*****@*****.**"} mail.send_mail(subject, body, recepients) print("Email gesendet.") else: print("Keine Email gesendet.")
def insert_table_beneficiarioans(self, DF, path): competencia = None status = None try: status = 2 #File processing completed competencia = self.check_competencia(path)[1] DF['COMPETENCIA'] = competencia DF['BENEFICIARIO_ID'] = DF.index DF['CONFERENCIA_ID'] = DF.index DF['CD_MUNICIPIO'].fillna(0, inplace=True) DF['NUMERO'].fillna(0, inplace=True) DF['LOGRADOURO'].fillna('nan', inplace=True) DF['BAIRRO'].fillna('nan', inplace=True) DF['COMPLEMENTO'].fillna('nan', inplace=True) DF['CD_MUNICIPIO_RESIDENCIA'].fillna(0, inplace=True) DF['CCO_BENEFICIARIO_TITULAR'].fillna(0, inplace=True) DF['CNPJ_EMPRESA_CONTRATANTE'].fillna(0, inplace=True) DF['CPF'].fillna(0, inplace=True) DF['CNS'].fillna(0, inplace=True) DF['CEP'].fillna(0, inplace=True) DF['RESIDE_EXTERIOR'].fillna(0, inplace=True) DF['NR_PLANO_ANS'].fillna(0, inplace=True) DF['REL_DEPEND'].fillna(0, inplace=True) DF['MTV_CANCELAMENTO'].fillna(0, inplace=True) DF['DT_ATUALIZACAO'] = '20' + DF['DT_ATUALIZACAO'].str[ 6:9] + '-' + DF['DT_ATUALIZACAO'].str[3:5] + '-' + DF[ 'DT_ATUALIZACAO'].str[0:2] DF['DT_NASCIMENTO'] = '20' + DF['DT_NASCIMENTO'].str[ 6:9] + '-' + DF['DT_NASCIMENTO'].str[3:5] + '-' + DF[ 'DT_NASCIMENTO'].str[0:2] DF['DT_CANCELAMENTO'] = '20' + DF['DT_CANCELAMENTO'].str[ 6:9] + '-' + DF['DT_CANCELAMENTO'].str[3:5] + '-' + DF[ 'DT_CANCELAMENTO'].str[0:2] DF['DT_CONTRATACAO'] = '20' + DF['DT_CONTRATACAO'].str[ 6:9] + '-' + DF['DT_CONTRATACAO'].str[3:5] + '-' + DF[ 'DT_CONTRATACAO'].str[0:2] for i in range(len(DF)): BAIRRO = str(DF.BAIRRO[i].replace("'", '')) LOGRADOURO = str(DF.LOGRADOURO[i].replace("'", '')) COMPLEMENTO = str(DF.COMPLEMENTO[i].replace("'", '')) SQL = ( f'''EXEC SP_INSERT_BENEFICIARIOANS @p_BENEFICIARIO_ID= '{DF.BENEFICIARIO_ID[i]}', @p_CCO= '{DF.CCO[i]}', @p_SITUACAO= '{DF.SITUACAO[i]}' , @p_dataAtualizacao= '{DF.DT_ATUALIZACAO[i]}', @p_CONFERENCIA_ID= '{DF.CONFERENCIA_ID[i]}', @p_LOGRADOURO= '{LOGRADOURO}', @p_NUMERO= '{DF.NUMERO[i]}', @p_COMPLEMENTO= '{COMPLEMENTO}', @p_BAIRRO= '{BAIRRO}', @p_codigoMunicipio= {DF.CD_MUNICIPIO[i]}, @p_codigoMunicipioResidencia= {DF.CD_MUNICIPIO_RESIDENCIA[i]}, @p_CEP= {DF.CEP[i]}, @p_resideExterior= {DF.RESIDE_EXTERIOR[i]}, @p_tipoEndereco= '{DF.TP_ENDERECO[i]}', @p_CPF= {DF.CPF[i]}, @p_CNS= {DF.CNS[i]}, @p_NOME= '{DF.NOME[i]}', @p_SEXO= '{DF.SEXO[i]}', @p_dataNascimento= '{DF.DT_NASCIMENTO[i]}', @p_nomeMae= '{DF.NOME_MAE[i]}', @p_ccoBeneficiarioTitular= {DF.CCO_BENEFICIARIO_TITULAR[i]}, @p_cnpjEmpresaContratante= {DF.CNPJ_EMPRESA_CONTRATANTE[i]}, @p_codigoBeneficiario= '{DF.CD_BENEFICIARIO[i]}', @p_dataCancelamento= '{DF.DT_CANCELAMENTO[i]}', @p_datacontratacao= '{DF.DT_CONTRATACAO[i]}', @p_itensExcluidosCobertura= '{DF.ITENS_EXCLUIDOS_COBERTURA[i]}', @p_motivoCancelamento= {DF.MTV_CANCELAMENTO[i]}, @p_numeroPlanoANS= {DF.NR_PLANO_ANS[i]}, @p_relacaoDependencia= {DF.REL_DEPEND[i]}, @p_COMPETENCIA= '{DF.COMPETENCIA[i]}' ''' ) db.execute(SQL) SendMail().sendMail(DF) #Send mail except Exception as e: competencia = self.check_competencia(path)[1] status = 3 #error processing the file ANS log.insert_log_error(str(e), 'insert_table_beneficiarioans') SendMail().sendMail(e) #Send mail db.rollback() finally: self.update_status_processing(status, competencia) db.commit() db.__disconnect__()
target_date = datetime.strptime("%s 06:00:00" % target_date, "%Y-%m-%d %H:%M:%S") season = decideSeason(target_date) if season == "summer": pass else: target_date = target_date + timedelta(hours=1) start_time = target_date - timedelta(days=5) end_time = target_date - timedelta(minutes=1) print("start_time = %s" % start_time) print("end_time = %s" % end_time) table_list = ["1m", "5m", "1h", "3h", "8h", "day"] master_count = [7200, 1440, 120, 40, 15, 5] message = "" for i in range(len(table_list)): sql = "select count(insert_time) from %s_%s_TABLE where insert_time >= \'%s\' and insert_time <= \'%s\' " % (instrument, table_list[i], start_time, end_time) response = con.select_sql(sql) length = response[0][0] message = message + "%s %s length check(expected_count - actual_count) = %s\n" % (instrument, table_list[i], master_count[i] - length) print(message) sendmail = SendMail("*****@*****.**", "*****@*****.**", property_path) sendmail.set_msg(message) sendmail.send_mail()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from receive_mail import FetchEmail from extract_content import extract_content from send_mail import SendMail # receivemail # 下载对应邮箱的附件图片,下载到对应的文件夹 received mail_server = '' username = '' password = '' # 此处填写授权码 fetch_email = FetchEmail(mail_server, username, password) emails = fetch_email.fetch_unread_messages() # 调用相应的代码进行处理,识别内容,生成xlsx save_dir_path = "to_send" extract_content(save_dir_path) # sendmail from_mail = '' tolist = [''] username = '' password = '' # 此处填写授权码 send = SendMail(from_mail, tolist, username, password) send.send_mail('./to_send')
def start(): # Command line arguments ap = argparse.ArgumentParser() ap.add_argument('-t', '--tune', type=bool, default=False, help="pass -t True for hyperparameter tuning") args = vars(ap.parse_args()) batch_size = 20 n_epochs = 1 # loads data and returns train, valid and test data train_load, valid_load, test_load, classes = load_data(batch_size) if not args['tune']: learning_rate = 0.001 optimizer = 'Adam' model = define_model() cr, op = loss_and_optim(model, learning_rate, optimizer) print("Training the network without hyperparameter tuning") train(n_epochs, model, train_load, valid_load, cr, op) accuracy = test(batch_size, model, test_load, classes, cr, op) accuracy = int(accuracy) with open('accuracy.txt', 'w') as f: f.write(str(accuracy)) else: n_epochs = 2 learning_rates = [0.01, 0.001] optimizers = ['Adam', 'SGD'] acc = [] max_acc = 0 best_lr = 0 best_opt = '' for learning_rate in learning_rates: for optimizer in optimizers: print( "\n ** Training with {} optimizer and {} learning rate **\n" .format(optimizer, learning_rate)) model = define_model() cr, op = loss_and_optim(model, learning_rate, optimizer) model = train(n_epochs, model, train_load, valid_load, cr, op) accuracy = test(batch_size, model, test_load, classes, cr, op) if accuracy > max_acc: max_acc = accuracy best_opt = optimizer best_lr = learning_rate # Save the best performing model torch.save(model.state_dict(), 'model_cifar.pt') print("Saving best model...") print( "\nBest Learning Rate : {}\nBest Optimizer : {}\nBest Accuracy: {}" .format(best_lr, best_opt, str(max_acc))) # Send email user about the model performance and best hyperparameter so far print("Sending email to the user...") s = SendMail(str(max_acc) + '%', best_lr, best_opt) s.send_mail() max_acc = int(max_acc) with open('accuracy.txt', 'w') as f: f.write(str(max_acc))
def main_process(): # 1. 调用receive_mail.py # 下载对应邮箱的附件图片,下载到对应的文件夹 received receiver_mail_server = config['receiver']['mail_server'] receiver_username = config['receiver']['username'] receiver_password = config['receiver']['password'] logger.info("Receive from mail_server is :{}, username is :{}!", receiver_mail_server, receiver_username, feature="f-strings") flag = True while flag: try: fetch_email = FetchEmail(receiver_mail_server, receiver_username, receiver_password) emails = fetch_email.fetch_unread_messages() logger.info("Receiving from mail_server...please wait...") if emails: flag = False logger.info("Receive mail attachment success!") time.sleep(1) except Exception as e: logger.debug("Receive mail attachment error, error is {}!", e, feature="f-strings") # 2. 调用extract_content.py # 对下载的图片进行识别,识别后内容生成xls try: save_dir_path = "to_send" extract_content(save_dir_path) logger.info("Extract mail attachment success!") except Exception as e: logger.debug("Extract mail attachment error, error is {}!", e, feature="f-strings") # 3. 调用sendmail.py # 将生成的xls发送到对应的邮箱列表 sender_mail_server = config['sender']['sender_mail_server'] to_username = config['sender']['to_username'] sender_username = config['sender']['sender_username'] sender_password = config['sender']['sender_password'] # 此处填写授权码 logger.info( "Send mail from sender_mail_server is :{}, sender_username is :{}, to_username is :{}!", sender_mail_server, sender_username, to_username, feature="f-strings") try: send = SendMail(sender_mail_server, to_username, sender_username, sender_password) send.send_mail('./to_send') logger.info("Send extract xls success!") except Exception as e: logger.debug("Send extract xls error, error is {}!", e, feature="f-strings")
import getpass import time import numpy as np from matplotlib import pyplot as plt from send_mail import SendMail from model import MobiFallNet from DataGenerator import MobiFallGenerator import os sender = input("Type email address from which you want to send alerts: ") password = getpass.getpass('Password:'******'STD': 0, 'WAL': 1, 'JOG': 2, 'JUM': 3, 'STU': 4, 'STN': 5, 'SCH': 6, 'CSI': 7, 'CSO': 8, 'FOL': 9, 'FKL': 10, 'BSC': 11, 'SDL': 12 }