Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176516
  • 博文数量: 13
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 832
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-16 22:43
个人简介

最近关注Python,Linux,LLVM

文章分类

全部博文(13)

文章存档

2014年(13)

分类: Python/Ruby

2014-03-02 17:37:23

有时想写一个小程序,接收几个命令行参数,输出一些信息。如果是‘hello,world’这种复杂度,sys模块和print函数就搞定了,但现实常常复杂那么一点点,查argparse和logging的文档是个体力活,容易被文档淹没,通常又不需要太复杂的功能,所以就抽空写了一个简单模板。

1.完整源码。

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """Python Demo Template.

  4. notes:
  5.   - log file will be created in CWD

  6. tips:
  7.   - itertools and operator may simplify sort and iterate
  8.   - sqlite3 may be helpful for your housekeeping file format

  9. """

  10. import argparse
  11. import logging
  12. import logging.config

  13. def main():
  14.     # all of command line arguments should be added here
  15.     parser = argparse.ArgumentParser(description='Python Demo Template')
  16.     parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
  17.                         default='-', help='text source [default: sys.stdin]')
  18.     parser.add_argument("-v", "--verbose", action="count", default=0,
  19.                        help="increase output verbosity")
  20.     args = parser.parse_args()

  21.     # runtime services: logging
  22.     env_init(args.verbose)
  23.     
  24.     # main logic begins
  25.     for line in args.infile:
  26.         logging.info(line.rstrip())

  27. def env_init(verbose):
  28.     # logging facility, only loglevel can be changed
  29.     if verbose >= 2:
  30.         loglevel = logging.DEBUG
  31.     elif verbose >= 1:
  32.         loglevel = logging.INFO
  33.     else:
  34.         loglevel = logging.WARNING

  35.     LOGGING = {
  36.         'version': 1,
  37.         'formatters': {
  38.             'simple': {
  39.                 'format': '%(levelname)s %(message)s'
  40.             },
  41.             'verbose': {
  42.                 'format': ('%(levelname)s %(asctime)s %(module)s '
  43.                            '%(process)d %(thread)d %(message)s')
  44.             },
  45.         },
  46.         'handlers': {
  47.             'console': {
  48.                'level': 'DEBUG',
  49.                'class': 'logging.StreamHandler',
  50.                'formatter': 'simple'
  51.             },
  52.             'file': {
  53.                 'level': 'INFO',
  54.                 'class': 'logging.handlers.RotatingFileHandler',
  55.                 'formatter': 'verbose',
  56.                 'filename': 'app.log',
  57.                 'maxBytes': 10*1024*1024,
  58.                 'backupCount': 5
  59.             },
  60.         },
  61.         'root': {
  62.             'level': loglevel,
  63.             'handlers': ['console', 'file']
  64.         },
  65.     }
  66.     logging.config.dictConfig(LOGGING)

  67. if __name__ == '__main__':
  68.     main()

2. 如果用Vim编辑代码,可以加一个autocmd,假设上述代码保存为py_main。

  1. "Python main template
  2. autocmd! BufNewFile *main.py 0r ~/.vim/templates/py_main

3. 用Vim新建以main.py为后缀的文件时,就会自动载入这个模板。

阅读(2481) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:浅析Python调用外部代码的三种方式(上篇)

给主人留下些什么吧!~~