import xmltodict
xml_data = open("example.xml", "r").read()
data_dict = xmltodict.parse(xml_data)
calories_min = 999999
min_food_name = ""
for food in data_dict['breakfast_menu']['food']:
food_name = food['name']
food_calories = int(food['calories'])
if food_calories<calories_min:
min_food_name, calories_min = food_name, food_calories
print("热量最低的食物:\n 名字:{}\n 热量:{}".format(min_food_name, calories_min))
print("name id")
import time
import datetime
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, LoggingEventHandler
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler, ThrottledDTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.log import LogFormatter
class ScriptEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self)
# 文件移动
def on_moved(self, event):
now = datetime.datetime.now()
if event.is_directory:
print("directory moved from {src_path} to {dest_path}".format(src_path=event.src_path,
dest_path=event.dest_path))
else:
print(
"file moved from {src_path} to {dest_path}".format(src_path=event.src_path, dest_path=event.dest_path))
logger.warning(f"from Neptune 时间为 {now} 文件 {event.src_path} 移动到 {event.dest_path}")
# 文件新建
def on_created(self, event):
now = datetime.datetime.now()
now = datetime.datetime.now()
if event.is_directory:
print("directory created:{file_path}".format(file_path=event.src_path))
else:
print("file created:{file_path}".format(file_path=event.src_path))
logger.warning(f"from Neptune 时间为 {now} 文件 {event.src_path} 新增")
# 文件删除
def on_deleted(self, event):
now = datetime.datetime.now()
if event.is_directory:
print("directory deleted:{file_path}".format(file_path=event.src_path))
else:
print("file deleted:{file_path}".format(file_path=event.src_path))
logger.warning(f"from Neptune 时间为 {now} 文件 {event.src_path} 删除")
# 文件修改
def on_modified(self, event):
now = datetime.datetime.now()
if event.is_directory:
print("directory modified:{file_path}".format(file_path=event.src_path))
else:
print("file modified:{file_path}".format(file_path=event.src_path))
logger.warning(f"from Neptune 时间为 {now} 文件 {event.src_path} 修改")
event_handler1 = ScriptEventHandler()
observer = Observer()
watch = observer.schedule(event_handler1,
path="D:\Python\learn\网络运维技术\FTP SMTP\name",
recursive=True)
# logging.basicConfig(level=logging.WARNING,
# format='%(asctime)s - %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S')
event_handler2 = LoggingEventHandler()
observer.add_handler_for_watch(event_handler2, watch) # 为watch新添加一个event handler
observer.start()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # Log等级总开关
# 第二步,创建一个handler,用于写入日志文件
logfile = 'id.log'
fh = logging.FileHandler(logfile, mode='a', encoding="utf-8") # open的打开模式这里可以进行参考
fh.setLevel(logging.WARNING) # 输出到file的log等级的开关
# 第三步,再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # 输出到console的log等级的开关
# 第四步,定义handler的输出格式
fh.setFormatter(LogFormatter())
ch.setFormatter(LogFormatter())
# 第五步,将logger添加到handler里面
logger.addHandler(fh)
logger.addHandler(ch)
authorizer = DummyAuthorizer()
# 添加用户权限与路径,参数(用户名,密码,用户目录,权限(见说明))
authorizer.add_user('nameid', '123456', "./name", perm="elradfmw")
handler = FTPHandler
handler.authorizer = authorizer
# 添加被动端口范围
handler.passive_ports = range(2000, 2334)
# 下载上传速度设置
dtp_handler = ThrottledDTPHandler
dtp_handler.read_limit = 300 * 1024 # 300kb/s
dtp_handler.write_limit = 300 * 1024 # 300kb/s
handler.dtp_handler = dtp_handler
# 监听IP和端口,Linux中需要root用户才能使用21端口
server = FTPServer(('127.0.0.1', 21), handler)
# 最大连接数
server.max_cons = 150
server.max_cons_per_ip = 15
server.serve_forever()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import quote
# 创建邮件主体对象
email = MIMEMultipart()
# 设置发件人、收件人和主题
email['From'] = 'from_email'
email['To'] = 'to_email'
email['Subject'] = Header('SMTP测试', 'utf-8')
content = ""
file_text = open("*.log", "r", encoding='utf-8')
while True:
contents = file_text.readline()
content = content + ""
+ contents + ""
if len(contents) == 0: # 读取内容长度为0,读取结束
break
file_text.close()
email.attach(MIMEText(content, 'html', 'utf-8'))
# 读取作为附件的文件
att1 = MIMEText(open('*.log', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="*.log"'
email.attach(att1)
# 创建SMTP_SSL对象(连接邮件服务器)
smtp_obj = smtplib.SMTP_SSL('smtp.fromemail.com', 465)
# 通过用户名和授权码进行登录
smtp_obj.login('fromemail', 'nitkersttphbheda')
# 发送邮件(发件人、收件人、邮件内容(字符串))
smtp_obj.sendmail(
'from_email',
'to_email',
email.as_string()
)
import threading
from time import sleep
import os
numPhilosophers = numChops = 0
class Philosopher(threading.Thread):
def __init__(self, index):
threading.Thread.__init__(self)
self.index = index
self.leftChop = chops[self.index]
self.rightChop = chops[((self.index + 1) % (numChops - 1))]
def run(self):
while True:
if int(self.index) % 2 == 1: # 奇数先拿左边的筷子
firstChop = self.rightChop
secondChop = self.leftChop
else:
firstChop = self.leftChop
secondChop = self.rightChop
firstChop.pickup()
secondChop.pickup()
self.dining()
secondChop.putdown()
firstChop.putdown()
self.resting()
def dining(self):
print("Philosopher {} starts to eat.".format(self.index))
sleep(0.5)
print("Philosopher {} finishes eating and leaves to rest.".format(self.index))
sleep(0.5)
def resting(self):
sleep(1)
class Chop():
def __init__(self, index):
self.index = index
self._lock = threading.Lock()
def pickup(self):
self._lock.acquire()
def putdown(self):
self._lock.release()
if __name__ == '__main__':
numPhilosophers = numChops = int(input()) + 1
# 创建筷子与哲学家实例
chops = [Chop(nnn) for nnn in range(numChops)]
philosophers = [Philosopher(nnn) for nnn in range(1, numPhilosophers)]
# 开启所有的哲学家线程
for philosopher in philosophers:
philosopher.start()
# 方便 CTRL + C 退出程序
try:
while True:
sleep(0.1)
except Exception as e:
raise e
import threading
from time import sleep
import os
class Rec_end(threading.Thread):
def __init__(self, index):
threading.Thread.__init__(self)
self.index = index
self.buffer = buffer
def run(self):
while True:
self.buffer.b_start()
self.receive()
self.buffer.b_end()
# self.rest()
def receive(self):
print("receiving end {} starts to receive.".format(self.index))
sleep(0.5)
print("receiving end {} finishes receiving and leaves to rest.".format(self.index))
sleep(0.4)
def rest(self):
sleep(1) # 自我阻塞1秒,让出机会执行下一个进程
class Buffer():
def __init__(self, index):
self.index = index
self._lock = threading.Lock()
def b_start(self):
self._lock.acquire()
def b_end(self):
self._lock.release()
if __name__ == '__main__':
numrec_ends = int(input()) + 1
# 创建接收端进程
buffer = Buffer(1)
rec_ends = [Rec_end(nnn) for nnn in range(1, numrec_ends)]
# 开启所有的接收端线程
for rec_end in rec_ends:
rec_end.start()
# 方便 CTRL + C 退出程序
try:
while True:
sleep(0.1)
except Exception as e:
raise e