zoukankan      html  css  js  c++  java
  • 第3章:打造命令行工具

    1.与命令行相关的Python语言特性

    1).使用sys.argv获取命令行参数

    import sys
    print(sys.argv)

    2).使用sys.stdin和fileinput读取标准输入

    import sys
    def get_content():
        return sys.stdin.readlines()
    print(get_content())
    使用Ctrl+d退出
    fileinput的使用非常简单,大部分情况下,我们直接调用fileinput模块的input方法按行读取内容即可
    用for循环遍历文件内容
    # cat read_from_fileinput.py 
    from __future__ import print_function
    import fileinput
    
    for line in fileinput.input():
        print(line, end=" ")
    
    # cat /etc/passwd | python read_from_fileinput.py

    3).使用SystemExit异常打印错误信息

    4).使用getpass库读取密码 

    import getpass
    user = getpass.getuser()
    passwd = getpass.getpass('your password: ')
    print(user,passwd)

    2.使用configparser解析配置文件

    import configparser
    cf = configparser.ConfigParser(allow_no_value=True)
    cf.read('/etc/my.cnf')
    print(cf.sections())
    print(cf.has_section('client'))
    print(cf.options('client'))
    print(cf.has_option('client','user'))
    print(cf.get('client','user'))

    3.使用argparse解析命令行参数

    1).ArgumentParse解析器

    import argparse
    
    def _argparse():
        parser = argparse.ArgumentParser(description="This is description")
        parser.add_argument('--host', action='store', dest='server', default="localhost", help='connect to host')
        parser.add_argument('-t', action='store_true', dest='boolean_switch', default=False, help='Set a switch to true')
        return parser.parse_args()
    
    def main():
        parser = _argparse()
        print(parser)
        print('host = ', parser.server)
        print('boolean_switch = ', parser.boolean_switch)
    
    if __name__ == '__main__':
        main()

     2).模仿MySQL客户端的命令行参数 

    import argparse
    
    def _argparse():
        parser = argparse.ArgumentParser(description='A Python-MySQL client')
        parser.add_argument('--host', action='store', dest='host', required=True, help='connect to host')
        parser.add_argument('-u', '--user', action='store', dest='user', required=True, help='user for login')
        parser.add_argument('-p', '--password', action='store', dest='password', required=True, help='password to use when connecting to server')
        parser.add_argument('-P', '--port', action='store', dest='port', default=3306, type=int, help='port number to use for connection or 3306 for default')
        parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.1')
        return parser.parse_args()
    
    def main():
        parser = _argparse()
        conn_args = dict(host=parser.host, user=parser.user, password=parser.password, port=parser.port)
        print(conn_args)
    
    if __name__ == '__main__':
        main()

    4.使用logging记录日志

    1).日志的作用

        诊断日志

        审计日志

    2).Python的logging模块

    import logging
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warn('warn message')
    logging.error('error message')
    logging.critical('critical message')

     3).配置日志格式 

    import logging
    import logging.config
    
    logging.config.fileConfig('logging.cnf')
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warn('warn message')
    logging.error('error message')
    logging.critical('critical message')

    5.与命令行相关的开源项目

    1).使用click解析命令行参数

    import click
    
    @click.command()
    @click.option('--count', default=1, help='Number of greetings.')
    @click.option('--name', prompt='Your name', help='The persion to greet.')
    def hello(count, name):
        for x in range(count):
            click.echo('Hello %s! '%name)
    
    if __name__ == '__main__':
        hello()

     2).使用prompt_toolkit打造交互式命令行工具

    from __future__ import unicode_literals
    from prompt_toolkit import prompt
    from prompt_toolkit.history import FileHistory
    
    while True:
        user_input =  prompt('>', history=FileHistory('history.txt'),)
        print(user_input)
  • 相关阅读:
    java的sha1加密,转化为python版本
    VUE:页面跳转时传递参数,及参数获取
    如何使用 Django中的 get_queryset, get_context_data和 get_object 等方法
    django orm 外键id返回对应的名称
    spring boot(一):入门篇
    redis学习(四)——Hash数据类型
    redis学习(三)——List数据类型
    redis学习(二)——String数据类型
    Java多线程(七)——线程休眠
    MySQL和B树的那些事
  • 原文地址:https://www.cnblogs.com/allenhu320/p/11323009.html
Copyright © 2011-2022 走看看