python练习5

1.请实现一个装饰器,每次调用函数时,将函数名字以及调用此函数的时间点写入文件中

import time

current_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

# 定义装饰器以记录函数执行的时间和结果
def record_execution_time(time_str):
    def decorator(func):
        def wrapper():
            with open("execution_log.txt", "a", encoding="utf-8") as log_file:
                # 记录时间、函数名
                log_file.write(f"时间点: {time_str}, 函数名: {func.__name__}\n")
                # 调用函数并记录结果
                result = func()
                log_file.write(f"执行结果: {result}\n")
        return wrapper
    return decorator

# 使用装饰器记录main函数的执行信息
@record_execution_time(current_time_str)
def main():
    return "Hello, World!"

if __name__ == '__main__':
    main()


2.编写一个装饰器,每执行一个函数,记录函数名称及函数执行时间,并写入log.text文件中

import time

def log_execution_time(file_path='log.txt'):
    def decorator(func):
        def wrapper(*args, **kwargs):
            start_time = time.time()
            result = func(*args, **kwargs)
            end_time = time.time()
            execution_time = end_time - start_time
            with open(file_path, 'a') as file:
                file.write(f"{func.__name__} executed in {execution_time:.6f} seconds\n")
            return result
        return wrapper
    return decorator

@log_execution_time()
def another_example():
    time.sleep(1)  # 模拟耗时操作
    print("Another function finished.")

another_example()


3.使用with语法完成文件的复制

def copy_file(src, dst):
    with open(src, 'r') as source_file:
        with open(dst, 'w') as destination_file:
            destination_file.write(source_file.read())

copy_file('source.txt', 'destination.txt')


4.完成登录系统,登录时数据使用序列化和反序列化

import pickle

class User:
    def __init__(self, username, password):
        self.username = username
        self.password = password

def serialize_user(user, file_path='user_data.pickle'):
    with open(file_path, 'wb') as file:
        pickle.dump(user, file)

def deserialize_user(file_path='user_data.pickle'):
    with open(file_path, 'rb') as file:
        return pickle.load(file)

# 登录模拟:序列化用户数据
new_user = User('Alice', 'password123')
serialize_user(new_user)

# 反序列化并验证登录
loaded_user = deserialize_user()
if loaded_user.username == 'Alice' and loaded_user.password == 'password123':
    print("Login successful!")
else:
    print("Login failed.")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值