3

我刚刚开始使用 Python,也许我担心得太早了,但无论如何......

log = "/tmp/trefnoc.log"

def logThis (text, display=""):
    msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
    if display != None:
        print msg + display
    logfile = open(log, "a")
    logfile.write(msg + "\n")
    logfile.close()
    return msg

def logThisAndExit (text, display=""):
    msg = logThis(text, display=None)
    sys.exit(msg + display)

这是有效的,但我不喜欢它的外观。有没有更好的方法来写这个(可能只有 1 个函数),在退出时我还有什么其他 需要注意的吗?


现在介绍一些背景(但不是关于trefnoc)......

有时我会打电话logThis只是为了记录和显示。其他时候我想调用它并退出。最初我是这样做的:

logThis ("ERROR. EXITING")
sys.exit()

然后我认为这不会正确设置stderr,因此当前代码显示在顶部。

我的第一个想法实际上是将“sys.exit”作为参数传递,并定义logThis ("ERROR. EXITING", call=sys.exit)如下(仅显示相关的差异部分):

def logThis (text, display="", call=print):
    msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
    call msg + display

但这显然行不通。我认为 Python 不会将函数存储在变量中。我无法(快速)找到任何地方,如果 Python 可以有变量接受函数或不!也许使用eval函数?我真的总是尽量避免他们,寿。当然,我想过使用if而不是另一个def,但这不会更好或更坏。

无论如何,有什么想法吗?

4

5 回答 5

2

“logThisAndExit”没有理由,它不会为您节省太多打字

sys.exit(logThis(text)+display)

(比较logThisAndExit(text, display)

或者

sys.exit(logThis(text))

(比较logThisAndExit(text)

并不是说我完全确定您为什么喜欢将退出消息格式化为日志行。

回答你原来的问题:你缺少括号:call(msg+display)工作正常。但我认为这对于记录/退出的东西来说是过度工程。维护您的代码的任何人都必须了解您的函数才能知道它何时退出以及何时不退出。

于 2010-04-14T00:21:49.937 回答
2

对于日志记录,使用日志记录模块可能更容易。

对于退出,如果您有任何错误,请使用:

sys.exit(1)

如果没有错误,要么让脚本用完语句,要么:

sys.exit(0)
于 2010-04-14T08:31:39.150 回答
1

您可以修改logThis以采用名为的最终参数shouldExit,默认为None,然后作为该方法的最后一步,如果值为 true 则调用sys.exit

于 2010-04-14T00:20:08.787 回答
1

print在 python < 3 中是关键字,而不是函数。试试这个:

def do_print(x):
    print x

def logThis (text, display="", call=do_print):
    msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
    call(msg + display)

你有什么理由不使用这个logging模块吗?(见http://onlamp.com/pub/a/python/2005/06/02/logging.html

于 2010-04-14T00:22:04.107 回答
0

作为参考,这是我吸收了 David 和 moshez 的提示后的最终代码。最后我决定我现在只需要 1 个函数。感谢大家!

log = "/tmp/trefnoc.log"

def logThis (text, display=""):
    msg = str(now.strftime("%Y-%m-%d %H:%M")) + " TREfNOC: " + text
    if display != None:
        print msg + display
    logfile = open(log, "a")
    logfile.write(msg + "\n")
    logfile.close()
    return msg

# how to call it on exit:
sys.exit(logThis("ERROR, EXITING", display=None))
于 2010-04-14T01:16:24.057 回答