简体   繁体   中英

How to print only once per execution in Python

I'm not a very experienced programmer, and I tried to find a library that contained a Python function that would print something only the first time this function was called from the same call and no more per script execution. Because I didn't find it, I created my own, and it works. But I don't know how to make it able to work just like print(f'') so I can include variables. Loops+break won't work here.

This is how it looks right now:

#dictionary so we don't have scope issues
already_printed = {}
def print_only_once(msg):
    try:
        testing = already_printed[msg]
    except KeyError:
        already_printed[msg] = msg
        print(msg)
    return

And I call it using:

print_only_once('my special message')

If this message has been printed before, it won't print again. I would like to be able to also do something like this:

print_only_once(f'temp is {var1} and humidity is {var2}')

And this special message would print only one time per script execution, regardless of how many times it was called, including with differente values for var1 and/or var2 from the first call.

Any help? Maybe there's something that does exactly that out there but I couldn't find it. Thanks a lot!

You can't do this when you format the string in the caller, because your function only receives the formatted string.

You need to have your function take the format string and values separately. Then you can save the format string in your dictionary, and call .format() explicitly.

already_printed = set()
def print_only_once(format_string, *args, **kwargs):
    if format_string not in already_printed:
        print(format_string.format(*args, **kwargs))
        already_printed.add(format_string)

print_only_once('temp is {var1} and humidity is {var2}', var1=var1, var2=var2)

Try doing something like this:

already_printed = []


def print_only_once(msg_name, msg):
    if msg_name not in already_printed:
        already_printed.append(msg_name)
        print(msg)
    return

I added another parameter called "msg_name". You should write what the message is about in there (like giving a group name). And you write your actual text/message in "msg".

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