defhello(name, age, sex, *args): print("Hello, My name is {name}.".format(name=name)) print("I'm {age} years old.".format(age=age)) print("I'm a {sex}".format(sex=sex))
if __name__ == "__main__": file_name = sys.argv[0] name = sys.argv[1] age = sys.argv[2] sex = sys.argv[3] other = sys.argv[4:] hello(name, age, sex, *other)
调用脚本:
1
python test_sysargv.py zhangsan 13 man nibi ss
脚本输出:
1 2 3 4 5 6
Hello, My name is zhangsan. I'm 13 years old. I'm a man Other word: nibi ss
defhello(name, age, sex, *args): print("Hello, My name is {name}.".format(name=name)) print("I'm {age} years old.".format(age=age)) print("I'm a {sex}".format(sex=sex))
if __name__ == "__main__": print("Format of transfer file: {type}".format(type=args.type)) if args.name and args.age and args.sex: hello(args.name, args.age, args.sex)
执行脚本:
1
python3 test_argparse.py -t json -n zhangsan -a 13 -s man
脚本成功输出:
1 2 3 4 5 6
Format of transfer file: json Hello, My name is zhangsan. I'm 13 years old. I'm a man Other word:
optional arguments: -h, --help show this help message and exit --name NAME, -n NAME name attribute: 非必要属性 --age AGE, -a AGE age attribute: 非必要属性 --sex SEX, -s SEX sex attribute: 非必要属性 --type TYPE, -t TYPE type attribute: 非必要属性