如何在Python中为所有print()输出设置前缀?

7

我正在使用Python在控制台打印输出。我需要一段代码,让所有在某行代码之后的print语句都以4个空格开头。例如:

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

输出:

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

这将有助于为包含在函数中的所有输出进行制表,以及设置函数输出何时进行制表。这种操作是否可行?
3个回答

6

您可以定义一个 print 函数,该函数首先打印您的前缀,然后内部调用内置的 print 函数。您甚至可以使您的自定义 print() 函数查看调用堆栈,并相应地确定要使用多少空格作为前缀:

import builtins
import traceback

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

测试一下:

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

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

func_f()

输出:

                    Printing from func_f
                     Printing from func_g

回到内置的print()函数:

当你完成自定义打印并想要开始使用内置的print()函数时,请使用del命令来“删除”你自己定义的print函数:

del print

2
为什么不定义自己的自定义函数,并在需要时使用它:

为什么不在需要时定义自己的自定义函数并使用它:

def tprint(*args):
    print('    ', *args)

它的使用方法如下:

最初的回答:

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

输出:

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

0

你可能想要在特定的地方使用特定的前缀

import sys
from contextlib import contextmanager

@contextmanager
def add_prefix(prefix): 
    global is_new_line
    orig_write = sys.stdout.write
    is_new_line = True
    def new_write(*args, **kwargs):
        global is_new_line
        if args[0] == "\n":
            is_new_line = True
        elif is_new_line:
            orig_write("[" + str(prefix) + "]: ")
            is_new_line = False
        orig_write(*args, **kwargs)
    sys.stdout.write = new_write
    yield
    sys.stdout.write = orig_write
    
with add_prefix("Computer 1"):
    print("Do something", "cool")
    print("Do more stuffs")
    
with add_prefix("Computer 2"):
    print("Do further stuffs")
print("Done")

#[Computer 1]: Do something cool
#[Computer 1]: Do more stuffs
#[Computer 2]: Do further stuffs
#Done

优点在于它是一个实用函数,即您只需导入即可使用,而无需每次编写新脚本时重新定义。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接