我目前正在撰写和学习装饰器(带有或不带有参数)。这是带有一个参数的修饰器的示例,该修饰符将函数的输出重定向到日志文件。该代码有效,但是我的问题如下:
提前谢谢!
def redirect_output(log_file): """ Decorator to redirect the stdout written output of a function to a specified log file. Args: log_file (str): The path to the log file where the output will be redirected. """ def redirect_output_decorator(func): @functools.wraps(func) def redirect_output_wrapper(*args, **kwargs) -> Any: output = StringIO() with redirect_stdout(output): func(*args, **kwargs) output_lines = output.getvalue().splitlines() if output_lines: file_logger("Output from {}: ".format(func.__name__), log_file) for line in output_lines: file_logger(line, log_file, with_date=False) return redirect_output_wrapper return redirect_output_decorator