【问题标题】:Redefine print to open, write in a log file, close重新定义打印打开,写入日志文件,关闭
【发布时间】:2017-09-30 16:06:16
【问题描述】:

背景:我注意到技巧nohup python test.py & 通常不起作用,因为输出未实时正确保存在nohup.out 中。给出in this famous question(如nohup python -u)的解决方案并不总是有效,如图in my other question here

问题:我的代码中到处都使用了print(...),所以我不想更改它并用另一个日志记录函数替换它。是否可以重新定义print 来代替:

from __future__ import print_function

def print(s):
    with open('out.txt', 'a+') as f:
        f.write(str(s) + '\n')
    old_print(s)     # how to print it with the standard print too?

【问题讨论】:

  • 您之前问题的第一个答案有什么问题?
  • @user2357112 如果我没记错的话,flush 的解决方案对我来说在 100% 的情况下都不起作用。
  • 如果flush 对您不起作用,那么没有理由期望close 会更好地工作。您可能应该调查 nohup 问题的根本原因;您现在所做的基本上是shot弹枪调试。
  • 打开、写入、关闭对我来说都可以(已经测试过),然后我会 100% 确定它会起作用。

标签: python python-2.7 logging nohup


【解决方案1】:

嗯,你可以重写内置函数。

考虑一下这个 test.py:

from __future__ import print_function

def new_print(*args, **kwargs):
    old_print('HELLO!')

import __builtin__
old_print = __builtin__.print
__builtin__.print = new_print

print(100)  # -> HELLO!
old_print(200)  # -> 200

如果您在单个模块中只重新定义一次内置函数,然后只导入它,这也有效 - 它会影响整个应用程序。

from __future__ import print_function
import test

print(300)  # HELLO!

但您仍然必须从 py2 中的 future 导入,始终如此。否则,print 将不是一个内置函数,而是一个运算符,因此永远不会被覆盖。

这个技巧也可以在 py3 中使用,除了模块名称是builtins。所以代码可能是这样的:

from __future__ import print_function

def new_print(*args, **kwargs):
    old_print('HELLO!')

try:
    import __builtin__ as bi  # py2
except ImportError:
    import builtins as bi # py3

old_print = bi.print
bi.print = new_print

print(100)
old_print(200)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2012-05-29
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多