【问题标题】:Appending to every printed message附加到每条打印的消息
【发布时间】:2012-06-12 23:18:42
【问题描述】:

简单的问题,我想在我调用的每个print 前面附加文本,例如,如果我将文本设置为hello 并运行:

print 'hello there'
print ' hi again'

它会打印这个:

hellohello there
hello hi again

有什么方法可以做到这一点,而不使用函数来使用它而不是print

【问题讨论】:

  • "stylize the printing" 不确定我理解这部分,能否请您改写一下?
  • 我的意思是创建一个刚刚调用 print 'hello' + message 的函数,我想编辑实际的 print 命令。
  • 为什么要避免为此创建函数?像def myPrint(text): print('hello '+text) 这样的东西确实是解决这个问题的方法。
  • @Junuxx - 因为我更喜欢使用print而不是另一个函数来打印。
  • @user1447941:我在类似的情况下使用过像“log()”或“say()”这样的函数名。虽然人们可能会为您提供重新定义 print 的骇人听闻的解决方案,但我真的建议您不要这样做。它只会在以后引起问题和混乱。

标签: python pretty-print


【解决方案1】:

您可以按照DevPlayer's post here on StackOverflow 覆盖打印,此处稍作修改:

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.
import sys

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    sys.stdout.write('hello')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")

[Edit] ...或者正如 DSM 建议的那样,您可以通过以下方式避免 sys 调用:

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    __builtins__.print('hello',end='')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")

【讨论】:

  • 这只是在我每次调用print 之前在新行上打印hello
  • 您可以将end='' 参数传递给打印函数,而不是使用sys.stdout.write
【解决方案2】:

您无法更改 Python 2 的打印语句,但您可以编写自己的类似文件的对象并使用它:

class PrefixedFile(object):
    def __init__(self, f, prefix):
        self.f = f
        self.prefix = prefix

    def write(self, s):
        s = s.replace("\n", "\n"+self.prefix)
        self.f.write(s)

sys.stdout = PrefixedFile(sys.stdout, "hello: ")

print "One"
print "Two"

请注意,这段代码不太有效,因为它在第一行缺少一个前缀,并在最后添加了一个,但你明白了! :)

【讨论】:

  • @JonCage:你可以改变打印函数,但是改变打印语句并不容易。
  • 是的,好吧,你让我到了那里:-)
  • @Ned:在替换sys.stdout 时,您知道社区的建议吗?当sys.stdout 被替换时,print 在幕后以非显式方式表现……我倾向于引入我自己的打印功能而不是替换sys.stdout,或者如果合适的话,也可以使用日志模块。我只会替换 sys.stdout 作为事后的想法。
  • 我同意替换 sys.stdout 是一种钝器,最好使用日志记录模块或自定义打印功能。
【解决方案3】:

即使 Jon Cage 的回答是替换 print() 函数的好方法,我还是建议改用您自己的打印函数(使用 Jon 的代码):

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.

def my_print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    print('hello', end='')
    print(*args, **kwargs)

与 Jon 的答案的唯一区别是您不要覆盖内置的 print()(“猴子补丁”)。我提倡这样做而不是修改print(),因为这使您的代码更易于维护,因为每个人都希望print() 是内置的。

my_print() 中使用print() 函数 代替print 语句,得到greater flexibility

【讨论】:

  • 我同意使用不同命名的函数更安全,但这不是 OP 要求的 ;-)
  • @JonCage:是的,他要求替换打印 statement,但没有一个答案提供这个,因为这很难。 :)
猜你喜欢
  • 2016-07-03
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
相关资源
最近更新 更多