1. import argparse
    2. def test_for_sys(year, name, body):
    3. print('the year is', year)
    4. print('the name is', name)
    5. print('the body is', body)
    6. parser = argparse.ArgumentParser(description='Test for argparse')
    7. parser.add_argument('--name', '-n', help='name 属性,非必要参数')
    8. parser.add_argument('--year', '-y', help='year 属性,非必要参数,但是有默认值', default=2017)
    9. parser.add_argument('--body', '-b', help='body 属性,必要参数', required=True)
    10. args = parser.parse_args()
    11. if __name__ == '__main__':
    12. try:
    13. test_for_sys(args.year, args.name, args.body)
    14. except Exception as e:
    15. print(e)

    执行时:

    1. python test_cmd.py -n Leijun --body "are you ok?"
    2. the year is 2017
    3. the name is Leijun
    4. the body is are you ok?

    原文链接:
    https://tendcode.com/article/python-shell/