简体   繁体   中英

Suppressing print output in python3 with file parameter

I have several functions that I want to set the verbosity level of. Currently, I'm handling it like so:

class Foo:
    def __init__(self, foo_stuff, verbose=True):
        self.print_file = None if verbose else open(os.devnull, 'w')

    def do_stuff(self):
        print('doing stuff', file=self.print_file)

This works, but I don't like that I never close the file self.print_file.

For cleanliness, I'd prefer not to wrap every single print function in a with open(...) . I was wondering if anyone could suggest another way of doing this. For this application, I don't think the python logging module will work.

atexit module may help. write a cleanup function in your Foo class and register it by calling

atexit.register(function, args)

to be called before your program exits.

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