Python:从类中缩进打印输出

时间:2016-02-09 14:55:15

标签: python python-3.x

如何从命令行中调用打印输出?我无法编辑类文件以向每个print()添加制表符。

所以我会在mypythonthing.py中调用导入的类:

print('Calling class')
MyClass()

然后所有的打印输出都会缩进,或者有一些前缀。

e.g。

$ python mypythonthing.py
$ Running your python script...
$ Calling class
$    > The print output from MyClass is indented
$    > Exiting MyClass
$

3 个答案:

答案 0 :(得分:2)

修补内置的print函数,为每行添加缩进。

import builtins

def print(*args, **kwargs):
    builtins.print("    > ", *args, **kwargs)

答案 1 :(得分:2)

如果你可以将应该缩进的代码(一个或多个)放在那么中,你可以使用装饰器来包装这些函数。

然后,这些函数内的print的任何调用都将缩进。 此外,您只需要在主脚本中声明此功能,而不是在其他任何地方声明。

示例 -

import builtins
import another # for demo purposes only

# This will override the default `print` function.
# Invoking it as a decorator will automatically perform
# initialisation and cleanup. There is also never a need
# to modify this.

def indent(f):
    def closure():
        old = builtins.print
        builtins.print = lambda x, *args, **kwargs:  old("\t>", x, *args, **kwargs)
        f()
        builtins.print = old
    return closure

some_number = "100"

# Example function, note decorator usage.
# This function may **not** take any parameters!
# It may however, use any variables declared before it.

@indent
def indentedStuffGoesHere():
    print("Inside `indentedStuffGoesHere`")
    print(some_number)
    another.Foo().bar()
    another.stuff()


print("entering special block")
indentedStuffGoesHere()
print("done")

another.py

def stuff():
    print("TESTING stuff")

class Foo:
    def bar(self):
        print("HELLO FROM FOO")

输出:

entering special block
    > Inside `indentedStuffGoesHere`
    > 100
    > HELLO FROM FOO
    > TESTING stuff
done

答案 2 :(得分:1)

我认为你可能正在寻找的是textwrap: textwrap docs 举个例子:

wrapper = textwrap.TextWrapper(width=preferredWidth, subsequent_indent='\t')
message = "asdf" * 50
print wrapper.fill(message)