带有日志记录和选项解析的Python控制台应用程序模板。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带有日志记录和选项解析的Python控制台应用程序模板。相关的知识,希望对你有一定的参考价值。

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3.  
  4. u"""Program name - short description
  5.  
  6. Example usage
  7. =============
  8.  
  9. .. sourcecode:: bash
  10.  
  11. python program_name.py -vvvvv action
  12.  
  13. :author: `Name Surname <mailto:[email protected]>`__
  14. """
  15.  
  16. # Pylint checks
  17. # "line to long" pylint: disable-msg=C0301
  18. # "Used * or ** magic" pylint: disable-msg=W0142
  19.  
  20. __revision__ = "$Id$"
  21. __docformat__ = 'restructuredtext en'
  22.  
  23. import os, sys, logging, optparse
  24.  
  25. #: Glogbal logger instance
  26. LOG = logging.getLogger(__name__)
  27. #: Debug level names as a string
  28. LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
  29. #: Console LOG format
  30. LOG_FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8st%(message)s'
  31. #: File LOG format
  32. LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
  33. #: Levels of logging translation (count of -v, log level)
  34. LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }
  35.  
  36. DEFAULT_VERBOSITY = 0
  37.  
  38.  
  39. def default_action():
  40. """ Does foo and bar """
  41. LOG.info("Default action done")
  42.  
  43. def main():
  44. """ Main function - parses args and runs action """
  45. parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog" + __revision__)
  46. parser.add_option("-v", action="count", dest="verbosity", default = DEFAULT_VERBOSITY, help = "Verbosity. Add more -v to be more verbose (%s) [default: %%default]" % LOG_HELP)
  47. parser.add_option("-l", "--logfile", dest="logfile", default = None, help = "Log to file instead off console [default: %default]" )
  48.  
  49. (options, args) = parser.parse_args()
  50.  
  51. verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)
  52.  
  53. # Set up logging
  54. if options.logfile is None:
  55. logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
  56. else:
  57. logfilename = os.path.normpath(options.logfile)
  58. logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
  59. print >> sys.stderr, "Logging to %s" % logfilename
  60.  
  61. # Run actions
  62. LOG.info("Starting %s, rev %s from %s using verbosity %s/%s as PID %d", __name__, __revision__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
  63.  
  64. for action in args:
  65. if action == 'raise':
  66. raise Exception("User requested exception")
  67. else:
  68. default_action()
  69.  
  70. LOG.info("Exited %s, rev %s from %s using verbosity %s/%s as PID %d", __name__, __revision__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
  71.  
  72. if __name__ == "__main__":
  73. main()

以上是关于带有日志记录和选项解析的Python控制台应用程序模板。的主要内容,如果未能解决你的问题,请参考以下文章

Blender Python 语句控制台日志记录

在 python 项目中如何记录日志

Python 选项解析器:带有可选参数的布尔标志

日志组件解析

python多处理日志记录:带有RotatingFileHandler的QueueHandler“文件被另一个进程使用”错误

.NetCore中的日志日志组件解析