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.")