V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ungrown
V2EX  ›  Python

让 argparse 也可以通过修饰器形式设置命令行参数

  •  
  •   ungrown ·
    ungrown · 2021-03-10 16:53:02 +08:00 · 1370 次点击
    这是一个创建于 1135 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://github.com/mo-han/mo-han-toolbox/blob/8e2e92d0c1b771155bac463f836da34a94982b29/mylib/ez/argparse.py

    单纯就是为了偷懒,形似 Click

    #test.py
    
    from mylib.ez.argparse import *
    from mylib.ez import AttrName
    
    pr = ParserRigger()
    ro = RawObject
    an = AttrName()  # an.attribute == 'attribute'
    
    
    @pr.super_command()
    @pr.argument(an.x)
    @pr.argument(an.y)
    @pr.argument(an.z)
    @pr.flag(an.l, help='print in multiple lines')
    @pr.call_map(an.x, ro(1111), an.z, UnknownArguments(), multi_line=an.l)
    def xyz(x, y, z, more, multi_line=False):
        print(f'x={x}', f'y={y}', f'z={z}', 'and more', *more, sep='\n' if multi_line else ', ')
    
    
    an.x = an.y = an.z = an.l = None
    
    pr.parse_known_args()
    pr.run()
    
    >test
    usage: test.py [-h] [-l] x y z
    test.py: error: the following arguments are required: x, y, z
    
    >test -h
    usage: test.py [-h] [-l] x y z
    
    positional arguments:
      x
      y
      z
    
    optional arguments:
      -h, --help  show this help message and exit
      -l          print in multiple lines
      
    >test 0 0 0 a b c
    x=0, y=1111, z=0, and more, a, b, c
    
    >test 0 0 0 a b c -l
    x=0
    y=1111
    z=0
    and more
    a
    b
    c
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4461 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:04 · PVG 12:04 · LAX 21:04 · JFK 00:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.