简体   繁体   中英

How to write a decorator for a function with an argument?

I would like to write a decorator to redirect stdout for the main function to a specific log file. The argument that the main function takes is - item, and I want the decorator to allocate a different log path with each item for the main function. How do I achieve this?

Currently I have:

def redirect_stdout(func):
    def wrapper():
        with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
            func(item)
    return wrapper()

@redirect_stdout
def main(item):

But I am not sure how the item argument goes into the decorator. Thanks!

What you are looking for is something like below

def redirect_stdout(func):
    def wrapper(item):
        with open(f"{log_path}{item}.log", "w") as log, contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
            func(item)
    return wrapper

To understand how this works you need to properly understand how the decorator works. Check below I have tried to explain how the decorator works. ==> I have used to indicate this is equivalent to.



@redirect_stdout
def main(item):
    pass

== >

def main(item):
    pass

main = redirect_stdout(main) = wrapper
---------
main(item) => wrapper(item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM