需求背景:为 python 脚本定义参数信息,从命令行获取脚本运行时传入的参数及订单号
import argparse
import sys
def parse_arg(cmd_parame):
parse = argparse.ArgumentParser(description='this is a demo')
parse.add_argument('order', type=str)
parse.add_argument('-e', '--env', type=str)
args = parse.parse_args(cmd_parame)
print(args)
print(args.order,args.env)
if __name__ == '__main__':
print(sys.argv[1:])
parse_arg(sys.argv[1:])
out:
PS C:\Users\86158\Desktop> python demo.py --env test FASO2024121
['--env', 'test', 'FASO2024121']
Namespace(order='FASO2024121', env='test')
FASO2024121 test
PS C:\Users\86158\Desktop> python demo.py FASO2024121 -e test
['FASO2024121', '-e', 'test']
Namespace(order='FASO2024121', env='test')
FASO2024121 test
PS C:\Users\86158\Desktop> python demo.py -h
['-h']
usage: demo.py [-h] [-e ENV] order
this is a demo
positional arguments:
order
options:
-h, --help show this help message and exit
-e ENV, --env ENV
PS C:\Users\86158\Desktop> python demo.py FASO2024121
['FASO2024121']
Namespace(order='FASO2024121', env=None)
FASO2024121 None
PS C:\Users\86158\Desktop> python demo.py
[]
usage: demo.py [-h] [-e ENV] order
demo.py: error: the following arguments are required: order
PS C:\Users\86158\Desktop>
参考资料:
标签:argparse,Python,demo,py,FASO2024121,env,test,order From: https://www.cnblogs.com/czzz/p/18088435