Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppressing print output in python3 with file parameter

Tags:

python

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.

like image 394
Ben Avatar asked Sep 11 '26 15:09

Ben


1 Answers

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.

like image 194
burkay Avatar answered Sep 14 '26 04:09

burkay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!