python - 附加到每条打印的消息

标签 python pretty-print

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

print 'hello there'
print ' hi again'

它会打印这个:

hellohello there
hello hi again

有什么方法可以做到这一点,而不使用函数来代替 print 吗?

最佳答案

您可以按照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")

[编辑] ...或者按照 DSM 的建议,您可以通过以下方式避免系统调用:

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")

关于python - 附加到每条打印的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11006199/

相关文章:

javascript - 是否有任何特别注意简洁的 JSON pretty-print ?

c++ - 使用格式不正确的 C++ 代码测试 prettyprinter

javascript - 是否有在线 JSON 查看器/格式化程序可以显示属性的路径?

python - AWS X-Ray 在服务 map 中显示重复节点

python - 如何使用 pyo3 从 Python 文件中调用 Rust 函数?

python - 退出python子进程中的无限进程

ocaml - 在 OCaml 中漂亮地打印一个 Hashtbl 以使用 ppx-deriving

haskell - 带有注释的 pretty-print 的 haskell 源代码

python - 浏览字典列表并仅选择存在键的行

python - 无序 Python 集的“顺序”