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
海納百川 ,有容乃大

浙公網安備 33010602011771號