在Python中编写'print'函数

2 投票
7 回答
5669 浏览
提问于 2025-04-16 01:03

我想创建一个函数,它的功能和Python内置的print函数差不多:

print 'test', i, 'started'

所以像这样调用应该可以工作:

log('test', i, 'started)

这个日志函数应该调用logging模块里的logging.info()函数。我该怎么创建这样一个函数呢?

这是我第一次尝试:

import logging
def log(*args):
    logging.info(args)

log('test', i, 'started)

但是输出的结果不是我想要的:

('test', 2, 'started')

而应该是这样的:

test 2 started

7 个回答

1

定义一个函数,这个函数可以接收任意数量的参数。你可以对这些参数列表 args 进行操作,按照你想要的方式打印出来:

>>> def log(*args):
...   print args

>>> log("a", 1, "b")
("a", 1, "b")

或者:

>>> def log(*args):
...   for a in args:  # <- loop over the arguments
...     print a,   # <- notice the comma that says "no newline".
...   print        # <- force a newline after the log statement.

>>> log("a", 1, "b")
a 1 b

如果你想使用 logging.info

logging.info(msg[, *args[, **kwargs]])

这个函数会在根日志记录器上记录一个信息级别的消息。传入的参数会像在 debug() 函数中那样被解释。

>>> def log(*args):
...   logging.info(" ".join("%s" %a for a in args))
3

你可以这样做:

def log(*args):
  logging.info(' '.join(args))
7

这个可以用:

def log(*args):
    logging.info(' '.join(map(str, args)))

撰写回答