第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)
原文地址:https://www.cnblogs.com/allenhu320/p/11323009.html