python总结
hell.py:
def get(file):
lsts = []
try:
with open(file,"r") as f:
for line in f:
lst = line.strip().split("\t")
lsts.append(lst)
except FileNotFoundError:
print(f"file not found:{file}")
return []
except Exception as e:
print(f"An error occurred: {e}")
return []
return lsts
def deal(input_,sep):
title_,expect_val = input_.split(sep)
title_ind = title_list[0].index(title_)
for line in line_list:
actual_val = line[title_ind]
dt_val = line[0]
yield actual_val,expect_val,dt_val
def entrypoint():
input_ = input("<<<")
if("<" in input_):
for actual_val,expect_val,dt_val in deal(input_,"<"):
if(actual_val < expect_val):
print("{0}: {1}".format(dt_val,actual_val))
elif(">" in input_):
for actual_val,expect_val,dt_val in deal(input_,">"):
if(actual_val > expect_val):
print("{0}: {1}".format(dt_val,actual_val))
elif("=" in input_):
for actual_val,expect_val,dt_val in deal(input_,"="):
if(actual_val == expect_val):
print("{0}: {1}".format(dt_val,actual_val))
else:
raise ValueError("Invalid comparison operator")
title_list = get("G:/人民币货币对.txt")
line_list = get("G:/人民币汇率中间价历史数据.txt")
entrypoint()
#要加上,否则打包exe时会闪退
input('输入任意字符结束')
用pip install pyinstaller,然后pyinstaller -F hello.py,可以看到dist目录有个hello.exe和__internal目录(上面的文件采用绝对路径,改成相对路径,将文件放在__internal目录),拷贝这两个可点击使用
ftpserver: from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler,ThrottledDTPHandler from pyftpdlib.servers import FTPServer from pyftpdlib.log import LogFormatter import logging logger = logging.getLogger() logger.setLevel(logging.INFO) ch= logging.StreamHandler() fh = logging.FileHandler(filename='ftpserver.log',encoding='utf-8') logger.addHandler(ch) logger.addHandler(fh) authorizer = DummyAuthorizer() authorizer.add_user("fpc","12345","D:/",perm="elradfmw") #authorizer.add_anonymous("D:/") handler = FTPHandler handler.authorizer = authorizer handler.passive_ports = range(2000,2333) dtp_handler = ThrottledDTPHandler dtp_handler.read_limit = 300*1024 dtp_handler.write_limit = 300*1024 handler.dtp_handler = dtp_handler server = FTPServer(("0.0.0.0",2121),handler) server.max_cons = 50 server.max_cons_per_ip = 15 server.serve_forever()
ftpclient: from ftplib import FTP FTP.port = 2121 ftp = FTP(host='127.0.0.1',user='fpc',passwd='12345') ftp.encoding = 'gbk' ftp.cwd('.') ftp.retrlines('LIST') ftp.retrbinary('RETR login.txt',open('login.txt','wb').write) ftp.storbinary('STOR 新文档.txt',open('新文档.txt','rb')) for f in ftp.mlsd(path='EditPlus 3'): print(f)
# -*- coding: UTF-8 -*- import smtplib from email.mime.text import MIMEText mail_host = 'smtp.163.com' mail_user = '13122968779' mail_pass = 'LZgBrrU7zBA3cQsT' sender = '13122968779@163.com' receivers = ["fangpcheng@qq.com"] message = MIMEText('<html>\ <head>\ <meta charset="utf-8" />\ <title></title>\ </head>\ <body>\ <div>\ <button id="bu">ceshi</button>\ </div>\ </body>\ </html>\ <script>\ document.getElementById("bu").onclick=function(){\ alert("我是回调函数")\ }\ </script>',"plain","utf-8") message["From"] = sender message["To"] = ";".join(receivers) message["Subject"] = "test" smtpobj = smtplib.SMTP() smtpobj.connect(mail_host,25) smtpobj.login(mail_user,mail_pass) smtpobj.sendmail(sender,receivers,message.as_string())
from watchdog.observers import Observer from watchdog.events import * import time class FileEventHandler(FileSystemEventHandler): def __init__(self): FileSystemEventHandler.__init__(self) def on_moved(self, event: DirMovedEvent | FileMovedEvent): now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) if event.is_directory: print(f"{now} 文件夹由{event.src_path}移动到{event.dest_path}") else: print(f"{now} 文件由{event.src_path}移动到{event.dest_path}") def on_created(self, event: DirCreatedEvent | FileCreatedEvent): now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) if event.is_directory: print(f"{now} 文件夹由{event.src_path}创建了") else: print(f"{now} 文件由{event.src_path}创建了") def on_deleted(self, event: DirDeletedEvent | FileDeletedEvent): now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) if event.is_directory: print(f"{now} 文件夹由{event.src_path}删除了") else: print(f"{now} 文件由{event.src_path}删除了") def on_modified(self, event: DirModifiedEvent | FileModifiedEvent) -> None: now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) if event.is_directory: print(f"{now} 文件夹由{event.src_path}修改了") else: print(f"{now} 文件由{event.src_path}修改了") if __name__ == "__main__": observer = Observer() path = r"F:\java_workspace" eventHandler = FileEventHandler() observer.schedule(eventHandler,path,recursive=True) observer.start() observer.join()
python发送简历邮件: import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.base import MIMEBase from email.header import Header from email import encoders mail_host = "smtp.163.com" mail_user = "13122968779" mail_pass = "VPHTzR9zN8fcCZbW" sender = "13122968779@163.com" receivers = ["fangpcheng@qq.com"] message = MIMEMultipart() message["From"] = sender message["To"] = ";".join(receivers) message["Subject"] = "test邮箱的主题" message.attach(MIMEText('<p>正文内容:测试带附件邮件发送</p><p>图片浏览:</p><p><img src="cid:image1"></p>',"html","utf-8")) fp = open("F:/1.png","rb") msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header("Content-ID","<image1>") message.attach(msgImage) # att1 = MIMEBase(open("F:/个人简历.doc","rb").read(),"base64","utf-8") # att1["Content-Type"] = "application/octet-stream" # att1["Content-Disposition"] = 'attachment:filename="个人简历.doc"' #message.attach(att1) # 添加Word附件(关键修正部分) file_path = "F:/个人简历.doc" with open(file_path, "rb") as f: # 使用MIMEBase处理二进制文件 part = MIMEBase("application", "msword") part.set_payload(f.read()) # 强制Base64编码 encoders.encode_base64(part) # RFC 5987编码解决中文文件名问题 filename = Header("个人简历11.doc", "utf-8").encode() part.add_header( "Content-Disposition", "attachment", filename=filename ) # 显式声明Content-Type part.add_header("Content-Type", "application/msword", name=filename) message.attach(part) smtpobj = smtplib.SMTP() smtpobj.connect(mail_host,25) smtpobj.login(mail_user,mail_pass) smtpobj.sendmail(sender,receivers,message.as_string())
实时报警
import smtplib import chardet import codecs import os from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart class txt2mail(): def __init__(self,host=None,auth_user=None,auth_password=None): self.host = "smtp.163.com" if host is None else host self.auth_user = "13122222779@163.com" if auth_user is None else auth_user self.auth_password = "UXaivuCcvBwQxegq" if auth_password is None else auth_password self.sender = "1312222279@163.com" def send_mail(self,subject,msg_str,recipient_list,attachment_list=None): message = MIMEMultipart() message["subject"] = Header(subject,"utf-8") message["From"] = self.sender message["To"] = Header(";".join(recipient_list),"utf-8") message.attach(MIMEText(msg_str,"plain","utf-8")) if attachment_list: for att in attachment_list: rbstr = open(att,"rb").read() attachment = MIMEText(rbstr,"base64","utf-8") attachment["Content-Type"] = "application/octet-stream" filename = os.path.basename(att) attachment.add_header( "Content-Disposition", "attachment", filename=("utf-8","",filename) ) message.attach(attachment) smtplibObj = smtplib.SMTP() smtplibObj.connect('smtp.163.com',25) # smtplibObj.login(self.auth_user,self.auth_password) smtplibObj.login(self.auth_user,self.auth_password) smtplibObj.sendmail(self.sender,recipient_list,message.as_string()) smtplibObj.quit() print("邮件发送成功") def get_chardet(self,filename): """ :param filename:传入一个文本文件 :return:返回文本文件的编码格式 """ encoding = None raw = open(filename,"rb").read() if raw.startswith(codecs.BOM_UTF8): encoding = "utf-8-sig" else: result = chardet.detect(raw) encoding = result["encoding"] return encoding def txt_send_mail(self,filename): ''' :param filename: 传入一个文件 :return: 将指定格式的txt文件发送到邮件,txt文本样例如下 someone1@xxx.com,someone2@xxx.com...#收件人,逗号分隔 xxx程序报警 #主题 程序xxx执行错误yyy,错误代码zzzz #正文 file1,file2 #附件,逗号分隔 ''' with open(filename,"r",encoding=self.get_chardet(filename)) as f: lines = f.readlines() recipient_list = lines[0].strip().split(",") subject = lines[1].strip() msgstr = "".join(lines[2:]) attachment_list = [] for line in lines[-1].strip().split(","): if os.path.isfile(line): attachment_list.append(line) print(recipient_list,subject,msgstr,attachment_list) self.send_mail( subject=subject, msg_str=msgstr, recipient_list=recipient_list, attachment_list=attachment_list ) if __name__ == "__main__": current_script_path = f"{os.path.dirname(__file__)}\\test.txt" print(current_script_path) t2mail = txt2mail() t2mail.txt_send_mail(current_script_path) 将指定文件解析发送邮件: test.txt: aaaa@qq.com,1234141234@163.com ntp2程序报警 程序ems执行错误yyy,错误代码12306 具体报错信息请查看附件: G:/cmd-k8s27.txt,G:/credentials.json
海纳百川 ,有容乃大