命令行解析工具argparse簡單使用-1

1、基本使用
#01.py

    import argparse

    parser = argparse.ArgumentParser()
    parser.parse_args()

$ python 01.py
$
$ python 01.py --help
usage: 01.py [-h]

optional arguments:
  -h, --help  show this help message and exit

2、位置參數
#02.py

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('echo')
    args = parser.parse_args()
    print args.echo

$ python 02.py
usage: 02.py [-h] echo
02.py: error: too few arguments

$ python 02.py --help
usage: 02.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit

#03.py

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('echo', help='echo the string you use here')
    args = parser.parse_args()
    print args.echo

$ python 03.py --help
usage: 03.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit

#04.py

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('square', help='display a square of a given number', type=int)
    args = parser.parse_args()
    print args.square ** 2


$ python 04.py --help
usage: 04.py [-h] square

positional arguments:
  square      display a square of a given number

optional arguments:
  -h, --help  show this help message and exit

$ python 04.py 3
9
$ python 04.py 4
16


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章