【问题标题】:Python print/output groupsPython 打印/输出组
【发布时间】:2020-07-24 13:41:42
【问题描述】:

JavaScript 为嵌套组打印提供了 console.group() 函数,我认为嵌套视图是一种更易于理解和更有条理的输出方式,但我不知道 Python 的内置或库等效项。

有吗?

寻找这样的东西:

def foo:
   ...
    bar()
def bar:
   ...

输出:

In foo fn
    foo 1
    In bar fn
        bar 1
        bar 2

【问题讨论】:

    标签: python io


    【解决方案1】:

    您可以使用“printGroup”代替常规的“print”

    indent = 0
    
    def group():
        indent += 1
    def groundEnd():
        indent -= 1
    def printGroup(str):
        print("\t"*indent+str)
    

    【讨论】:

    • 这不会扩展到其他类,除非您提供 indent 作为每个函数的参数
    • 然后你可以在你的程序中创建一个“console”类,在该类中使用“indent”静态变量和其他静态函数。
    • 这似乎是唯一的选择,它在技术上是正确的,但我希望 Python 有一个类似的内置日志记录选项,以避免必须在每个其他选项中导入 console 类。就是这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2020-02-29
    相关资源
    最近更新 更多