在Linux环境调用python脚本,需要从外部传参,python提供了两种传参方式:

1.顺序传参

import sys
它封装了与python解释器相关的数据,在脚本里面使用使用参数的顺序必须和传参顺序一致

import sys
print("传入参数的总长度为:",len(sys.argv))
print("type:",type(sys.argv))
print("function name:",sys.argv[0])
try:
    print("name:",sys.argv[1])
    print("age:",sys.argv[2])
    print("sex:",sys.argv[3])
except Exception as e:
    print("Input Error:",e)

在命令行调用该脚本,输出为:

E:\biancheng\python\Tiantian_learning>python Compute.py Tom 18 boy
传入参数的总长度为: 4
type: <class 'list'>
function name: Compute.py
name: Tom
age: 18
sex: boy

如果多传了参数,则多余的参数会被舍弃:

E:\biancheng\python\Tiantian_learning>python Compute.py Tom 18 boy hello
传入参数的总长度为: 5
type: <class 'list'>
function name: Compute.py
name: Tom
age: 18
sex: boy

如果少传了,则会报错:

E:\biancheng\python\Tiantian_learning>python Compute.py Tom
传入参数的总长度为: 2
type: <class 'list'>
function name: Compute.py
name: Tom
Input Error: list index out of range

2.不按顺序传参

import argparse

import argparse
parser = argparse.ArgumentParser(description='argparse testing')
parser.add_argument('--name','-n',type=str, default = "Tom",required=True,help="a student's name")
parser.add_argument('--age','-a',type=int, default=18,help='age of the student')
parser.add_argument('--sex','-s',type=str, default='boy',help="sex of the student")
parser.add_argument('--favorite','-f',type=str, nargs="+",required=False,help="favorite of the student")

args = parser.parse_args()
print(args.name)
print(args.age)
print(args.sex)
print(args.favorite)

不按照顺序的传参输出:

E:\biancheng\python\Tiantian_learning>python Compute.py --name Lin --age 13 --favorite food --sex boy
Lin
13
boy
['food']

参数使用:

--xx  完整参数输入
-x    简写参数输入
type  输入的参数将要被转换的数据类型
default 默认值
help   参数介绍
nargs  可传入的参数数量
required  是否为必须参数

简写参数输入:

E:\biancheng\python\Tiantian_learning>python Compute.py -n Lin -a 13 -f food -s boy
Lin
13
boy
['food']

使用默认参数:

E:\biancheng\python\Tiantian_learning>python Compute.py -f football -n Tom
Tom
18
boy
['football']

多个参数:

E:\biancheng\python\Tiantian_learning>python Compute.py -f football food music -n Tom
Tom
18
boy
['football', 'food', 'music']

关于argparse的更多使用请参考官方介绍:argparse

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐