如何组合已知参数和变量参数以将它们传递给另一个函数?

时间:2015-07-30 22:37:34

标签: python argument-passing

我在Python中看到了关于变量参数的以下SO帖子:

What does ** (double star) and * (star) do for parameters?
function call with named/unnamed and variable arguments in python
Can a variable number of arguments be passed to a function?

他们都没有回答我的问题。所以,在这里:

我想定义几个函数:

def LogError(log_file, *args):
  print("USER ERROR:", ***NOT SURE ABOUT THIS PART***, file=log_file)

def LogWarning(log_file, *args):
  print("USER WARNING:", ***NOT SURE ABOUT THIS PART***, file=log_file)

我想用他们打电话给他们:

error_file = open("somefile")
LogError(error_file, "Unable to find", username, "in the database.")

warning_file = open("somefile")
LogWarning(warning_file, arg1, arg2, arg3)

我希望LogError的调用等同于

print("USER ERROR:", "Unable to find", username, "in the database.", file=error_file)

我希望LogWarning的调用等同于

print("USER WARNING:", arg1, arg2, arg3, file=warning_file)

实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

您拥有的第一个链接应该提供答案

def LogError(log_file, *args):
  print("USER ERROR:", *args, file=log_file)

def LogWarning(log_file, *args):
  print("USER WARNING:", *args, file=log_file)

那会根据你的需要扩展参数。但是,不应该制定自己的解决方案,而应该改为python's built in logging feature

答案 1 :(得分:0)

只需加入空格即可,因为无论如何这都是最终结果:

print('USER ERROR: {}'.format(' '.join(*args)), file=error_file)

你真的应该使用logging module,这会让你的生活更轻松:

import logging

# Create a logger
log = logging.getLogger(__file__)

# Set the output for different log levels
# this is optional, you can write out all errors to the
# console and do many combinations, such as sending emails

warning_logger = logging.FileHandler('warnings.log')
warning_logger.setLevel(logging.WARNING)

error_logger = logging.FileHandler('error.log')
error_logger.setLevel(logging.ERROR)

# Set the format of messages
# levelname will be WARNING or ERROR depending on the message
log_format = logging.Formatter('USER %(levelname)s: %(message)s')

# Set the formatters for the error loggers
warning_logger.setFormatter(log_format)
error_logger.setFormatter(log_format)

# Add the handlers to the master logger instance
log.addHandler(warning_logger)
log.addHandler(error_logger)

# Now all you need is

log.warn('This is a warning')
log.error('This is a error')

有关详细信息,请查看logging module documentation,有关更多食谱,logging module cookbook值得一读。