如何将函数结果和调用它的字符串传递给函数?

2024-06-16 09:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数plog(),它记录函数和所述函数的输出,以避免每次键入完整的日志命令。你知道吗

>>> #! python
...
>>> import logging
>>>
>>> def plog(output, command):
...     logging.debug('{} enumerates as {}'.format(str(command), str(output)))
...
>>> logging.basicConfig(level=logging.DEBUG,
...                     format='%(asctime)s - %(levelname)s - %(message)s')
>>> plog(type(True), 'type(True)')
2019-04-28 14:40:01,154 - DEBUG - type(True) enumerates as <class 'bool'>

然而,在给plog打电话时重复我自己似乎很愚蠢——有没有一种方法可以让我基本上打电话:

>>> plog(type(True))

并接收相同的输出?你知道吗


Tags: 函数debug命令trueformatoutput键入logging
2条回答

可以使用eval()命令执行传递给方法的字符串:

def plog(command): logging.debug('{} enumerates as {}'.format(command, eval(command)))

然后可以将应作为字符串执行的代码传递给方法:

plog("type(True)")

正如@Tomothy32所建议的,使用eval()并不是最好的解决方案。 不使用eval(),您可以执行以下操作:

def plog(command, *args):
    method_call_str = "{}({})".format(command.__name__  ,", ".join(str(a) for a in args));
    logging.debug("{} enumerates to {}".format(method_call_str , command(*args)))

您需要将方法调用更改为例如:

plog(max, 1, 2)

这将导致:max(1, 2) enumerates to 2

相关问题 更多 >