有时想写一个小程序,接收几个命令行参数,输出一些信息。如果是‘hello,world’这种复杂度,sys模块和print函数就搞定了,但现实常常复杂那么一点点,查argparse和logging的文档是个体力活,容易被文档淹没,通常又不需要太复杂的功能,所以就抽空写了一个简单模板。
1.完整源码。
-
#!/usr/bin/env python
-
# -*- coding: utf-8 -*-
-
"""Python Demo Template.
-
-
notes:
-
- log file will be created in CWD
-
-
tips:
-
- itertools and operator may simplify sort and iterate
-
- sqlite3 may be helpful for your housekeeping file format
-
-
"""
-
-
import argparse
-
import logging
-
import logging.config
-
-
def main():
-
# all of command line arguments should be added here
-
parser = argparse.ArgumentParser(description='Python Demo Template')
-
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
-
default='-', help='text source [default: sys.stdin]')
-
parser.add_argument("-v", "--verbose", action="count", default=0,
-
help="increase output verbosity")
-
args = parser.parse_args()
-
-
# runtime services: logging
-
env_init(args.verbose)
-
-
# main logic begins
-
for line in args.infile:
-
logging.info(line.rstrip())
-
-
def env_init(verbose):
-
# logging facility, only loglevel can be changed
-
if verbose >= 2:
-
loglevel = logging.DEBUG
-
elif verbose >= 1:
-
loglevel = logging.INFO
-
else:
-
loglevel = logging.WARNING
-
-
LOGGING = {
-
'version': 1,
-
'formatters': {
-
'simple': {
-
'format': '%(levelname)s %(message)s'
-
},
-
'verbose': {
-
'format': ('%(levelname)s %(asctime)s %(module)s '
-
'%(process)d %(thread)d %(message)s')
-
},
-
},
-
'handlers': {
-
'console': {
-
'level': 'DEBUG',
-
'class': 'logging.StreamHandler',
-
'formatter': 'simple'
-
},
-
'file': {
-
'level': 'INFO',
-
'class': 'logging.handlers.RotatingFileHandler',
-
'formatter': 'verbose',
-
'filename': 'app.log',
-
'maxBytes': 10*1024*1024,
-
'backupCount': 5
-
},
-
},
-
'root': {
-
'level': loglevel,
-
'handlers': ['console', 'file']
-
},
-
}
-
logging.config.dictConfig(LOGGING)
-
-
if __name__ == '__main__':
-
main()
2. 如果用Vim编辑代码,可以加一个autocmd,假设上述代码保存为py_main。
-
"Python main template
-
autocmd! BufNewFile *main.py 0r ~/.vim/templates/py_main
3. 用Vim新建以main.py为后缀的文件时,就会自动载入这个模板。
阅读(2533) | 评论(0) | 转发(0) |