美文网首页python之路
python命令行解析的几个模块

python命令行解析的几个模块

作者: 非鱼2018 | 来源:发表于2019-11-13 21:33 被阅读0次

为了演示方便,写了个小demo

import sys
def filter_exclude(*arglist,exclude=None):
    results=[]
    if exclude is None:
        return arglist
    else:
        for i in arglist:
            if exclude not in i:
                results.append(i)

    return results

def filter_include(*arglist,include='all'):
    results=[]
    if include=='all':
        return arglist

    for i in arglist:
        if include in i:
            results.append(i)
    return results

def run(include='all',exclude=None):
    list1 = ['beijing', 'shanghai', 'shenzhen','shenzhen longhua']
    res = filter_include(*list1, include=include)
    print(res)
    res2 = filter_exclude(*res, exclude=exclude)
    print(res2)
if __name__=='__main__':
    run()

1.命令行参数,要写一大堆东西,判断用户提供了多少个参数

if __name__=='__main__':

     if len(sys.argv)==3:
         run(sys.argv[1],sys.argv[2])
     if len(sys.argv)==2:
         run(sys.argv[1])
     if len(sys.argv) ==1:
         run()
    #调用:fire_demo.py shenzhen longhua

2.argparse模块,更加灵活,python内置库,不需要安装

import argparse
parse=argparse.ArgumentParser()
parse.add_argument("-i","--include",help='包含的',default='all')
parse.add_argument("-e", "--exclude", help='排除的')
args=parse.parse_args()
run(args.include,args.exclude)

 #调用:fire_demo.py shenzhen longhua
# fire_demo.py -i shenzhen --exclude longhua

3.fire模块只需要一行代码,只需要一行,轻松搞定,谷歌出品,需要安装

   import fire
   fire.Fire(run)

   # 调用:fire_demo.py shenzhen longhua
    #fire_demo.py include shenzhen
    # fire_demo.py run include shenzhen
    #fire_demo.py - -include shenzhen - -exclude longhua

4.其他命令行解析模块,如click,getopt,大家可以自行研究,不过个人觉得有fire模块,完全就够用了,而且很强大

相关文章

  • rpdb2源码分析(2)

    11、怎么解析命令行参数? 使用getopt模块。请参考: Python命令行:getopt模块详解https:/...

  • DL中遇到的语法问题

    python语法 1.argparse模块 python中用于命令行解析的模块。 使用方法 import argp...

  • python argparse模块

    argparse是一个python中的命令行解析模块 parser = argparse.ArgumentPars...

  • Python argparse介绍

    argparse 模块是 Python 标准库中推荐的命令行解析模块。用来写命令行脚本十分好用。 命令行分三种情况...

  • python命令行解析的几个模块

    为了演示方便,写了个小demo 1.命令行参数,要写一大堆东西,判断用户提供了多少个参数 2.argparse模块...

  • Argarse教程

    本教程旨在简要介绍Python标准库中推荐的命令行解析模块 Argparse教程 argparse是Python内...

  • Python | argparse

    参考:博客园 | Python解析命令行读取参数 -- argparse模块[https://www.cnblog...

  • argparse模块

    argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块 使用步骤...

  • Python--argparse 模块

    一、简介 argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块...

  • Python库之argparse使用

    argsparse是python的命令行解析的标准模块. 下载地址: https://pypi.org/proje...

网友评论

    本文标题:python命令行解析的几个模块

    本文链接:https://www.haomeiwen.com/subject/ggoeyctx.html