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)
复制代码

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# -*- 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
复制代码

 

posted @   fangpengcheng_方鹏程  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 深度对比:PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
  1. 1 黄昏 周传雄
黄昏 - 周传雄
00:00 / 00:00
An audio error has occurred.

作词 : 陈信荣

作曲 : 周传雄

编曲 : 周传雄

制作人 : 周传雄

过完整个夏天

忧伤并没有好一些

开车行驶在公路无际无边

有离开自己的感觉

唱不完一首歌

疲倦还剩下黑眼圈

感情的世界伤害在所难免

黄昏再美终要黑夜

依然记得从你口中说出再见坚决如铁

昏暗中有种烈日灼身的错觉

黄昏的地平线

划出一句离别

爱情进入永夜

依然记得从你眼中滑落的泪伤心欲绝

混乱中有种热泪烧伤的错觉

黄昏的地平线

割断幸福喜悦

相爱已经幻灭

唱不完一首歌

疲倦还剩下黑眼圈

感情的世界伤害在所难免

黄昏再美终要黑夜

依然记得从你口中说出再见坚决如铁

昏暗中有种烈日灼身的错觉

黄昏的地平线

划出一句离别

爱情进入永夜

依然记得从你眼中滑落的泪伤心欲绝

混乱中有种热泪烧伤的错觉

黄昏的地平线

割断幸福喜悦

相爱已经幻灭

依然记得从你口中说出再见坚决如铁

昏暗中有种烈日灼身的错觉

黄昏的地平线

划出一句离别

爱情进入永夜

依然记得从你眼中滑落的泪伤心欲绝

混乱中有种热泪烧伤的错觉

黄昏的地平线

割断幸福喜悦

相爱已经幻灭

配唱制作人 : 吴佳明

钢琴 : 周传雄

吉他 : 许华强

鼓 : Gary&nbsp;Gideon

贝斯 : Andy&nbsp;Peterson

弦乐编写 : 吴庆隆

弦乐 : 孔朝晖/顾文丽/隋晶晶/梁中枢/尹淑占/王言/关旗

和声编写 : 周传雄

和声 : 周传雄

录音师 : 林世龙/沈文钏/Geoffrey Lee

混音师 : 王晋溢

录音室 : 强力/HASAYAKE/Atomic&nbsp;&amp;&nbsp;Audioplex&nbsp;(Singapore)

混音室 : 白金

OP : Sony/ATV&nbsp;Music&nbsp;Publishing&nbsp;Taiwan/哈萨雅琪有限公司

SP : Sony/ATV&nbsp;Music&nbsp;Publishing&nbsp;Taiwan​

点击右上角即可分享
微信分享提示