所有打印功能都带有标签。蟒

时间:2017-10-22 20:12:19

标签: python python-3.x

如何将'\ t'附加到函数中的所有打印件?

示例:

def func():
   print('this print with tab')
   print('and this print with tab')

print('some text:')
func()

代码输出应为:

some text:
   this print with tab
   and this print with tab

代码func()的输出应该没有标签:

this print with tab
and this print with tab

所以,我认为它应该像装饰器一样func。

4 个答案:

答案 0 :(得分:2)

选项1:使用单独的方法

定义方法:

def tprint(*args, **kwargs):
  print('\t', *args, **kwargs)

然后调用它而不是print

选项2:使用装饰器

受到vaultah答案的启发:

def maketabbed(func):
    def tabbed():
      output = io.StringIO()
      with contextlib.redirect_stdout(output):
        func()
      for line in output.getvalue().splitlines():
        print('\t' + line)
    return tabbed

@maketabbed
def func():
  print('this print with tab')
  print('and this print with tab')

答案 1 :(得分:1)

暂时将STDOUT重定向到类似文件的对象并调用您的函数。然后读取缓冲区的全部内容并调用textwrap.indent缩进每一行:

import io, textwrap
from contextlib import redirect_stdout

output = io.StringIO()
with redirect_stdout(output):
    func()

print(textwrap.indent(output.getvalue(), '\t'), end='')

输出

some text:
    this print with tab
    and this print with tab

答案 2 :(得分:0)

只需定义一个预先添加标签的功能。

def myPrintTab(*msg):
    print("\t",*msg)

然后在需要的地方使用它而不是打印。

答案 3 :(得分:0)

您可以引入一个可选的参数来触发'\t'

def func(t=False):
   t = '\t' if t else ''
   print(t + 'this print with tab')
   print(t + 'and this print with tab')

print('some text:')
func(True)