第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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值