printf quiet mode

Python framework for working with atomic configurations, potentials, and algorithms.

Moderator: moderators

Post Reply
ryeterrell
Posts: 23
Joined: Fri Jun 27, 2008 8:49 pm

printf quiet mode

Post by ryeterrell »

I've been trying to figure out a way to make functions quiet. I don't have any elegant way to do it yet, but here's what I have so far:

- Every function that prints anything is required by convention to possess a "quiet" parameter, defaulted to false.
- Every function that prints anything is required by convention to use the printf module to print.
- When calling the printf module, the "quiet" parameter is passed along to printf.
- Printf determines, though a combination of the "quiet" parameter and the warnlevel, whether or not to print anything.

Example of use:

Code: Select all

def foo(a, b, quiet = False):
    printf( a + " just foobared " + b, ALL, quiet = quiet)

foo("Rye", "Matt", quiet = True)
# prints nothing

foo("Rye", "Matt")
# prints "Rye just foobared Matt"
Any thoughts?

-Rye
matt
Posts: 37
Joined: Thu Jul 17, 2008 10:51 pm

Re: printf quiet mode

Post by matt »

The problem with this is that if we implement it, then decide that we don't want it, it will be quite annoying to remove. Is there any way that we could just pass the function and a tuple of its arguments to a "silence" function, and that function would then do everything necessary to call that function without making noise? The actual implementation of silence might be a bit tricky, but that way, we only have to change one thing if we find bugs.
ryeterrell
Posts: 23
Joined: Fri Jun 27, 2008 8:49 pm

Re: printf quiet mode

Post by ryeterrell »

Can you give an example of what you have in mind? I'm a bit lost.
lumengna
Posts: 1
Joined: Sat Feb 16, 2019 1:04 am

Re: printf quiet mode

Post by lumengna »

An easier way to do this is to create a wrapper function like this (sorry I don't know how to turn on code format):

class SuppressPrint:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = None

def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self._original_stdout

You can then wrap a function you want to silence by using a with statement:

with SuppressPrint():
[your code / functions here]

This will ignore all print statements. If you need something more dynamic, you can wrap this with a function as well with a parameter ("quiet" in your example).
Post Reply