Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a prefix for all print() output in python?

I am printing to a console in python. I am looking for a one off piece of code so that all print statments after a line of code have 4 spaces at the start. Eg.

print('Computer: Hello world')
print.setStart('    ')
print('receiving...')
print('received!')
print.setStart('')
print('World: Hi!')

Output:

Computer: Hello world
    receiving...
    received!
World: Hi!

This would be helpful for tabbing all of the output that is contained in a function, and setting when functions output are tabbed. Is this possible?

like image 243
Dave Avatar asked Mar 18 '19 05:03

Dave


People also ask

How do you print all output in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

How do you take the prefix of a string in Python?

There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .


1 Answers

You can define a print function which first prints your prefix, and then internally calls the built-in print function. You can even make your custom print() function to look at the call-stack and accordingly determine how many spaces to use as a prefix:

import builtins
import traceback

def print(*objs, **kwargs):
    my_prefix = len(traceback.format_stack())*" "
    builtins.print(my_prefix, *objs, **kwargs)

Test it out:

def func_f():
    print("Printing from func_f")
    func_g()

def func_g():
    print ("Printing from func_g")

func_f()

Output:

                    Printing from func_f
                     Printing from func_g

Reverting back to the built-in print() function:

When you are done with your custom printing, and want to start using the built-in print() function, just use del to "delete" your own definition of print:

del print
like image 190
fountainhead Avatar answered Sep 28 '22 12:09

fountainhead