python脚本传入参数
背景
在日常使用一些数据处理脚本以及训练模型的时候,使用传递参数很常见,因此对使用python进行参数传递的方式进行了整理
1.使用sys.argv的数组进行传参
使用sys.argv必须按照先后的顺序传入对应的参数;sys.argv则封装了传入的参数数据,作为数组的方式进行传入。
1 | import sys |
运行的output:1
2
3
4
5
6传入参数: ['py_test.py', 'one', 'two']
传入参数的总长度为: 3
type: <class 'list'>
function name: py_test.py
第一个传入的参数为: one
第二个传入的参数为: two
2.使用argparse包传入
args.add_argument的方法的type参数理论上可以是任何合法的类型,而且传入的顺序没有要求,这点来说比较方便,因此在现在脚本的编写上,使用argparse包越来越常见。
1 | import argparse |
3.通过shell脚本的形式进行传参
3.1 使用shell脚本向python脚本进行传参
python 脚本依旧使用sys.argv的数组方式进行传入。
python文件:py_test.py1
2
3
4
5
6
7
8
9
10import sys
print("传入参数的总长度为:", len(sys.argv))
print("type:", type(sys.argv))
print("function name:", sys.argv[0])
try:
print("第一个传入的参数为:", sys.argv[1])
print("第二个传入的参数为:", sys.argv[2])
except Exception as e:
print("Input Error:", e)
shell脚本文件:py_test_shell.sh1
2
3
4
5!/bin/bash
定义变量
para1=$
1para2=$2
python python_test.py $para1 $para2
终端执行命令:sh py_test_shell.sh test01 test021
2
3
4
5传入参数的总长度为: 3
type: <class 'list'>
function name: py_test.py
第一个传入的参数为: test01
第二个传入的参数为: test02
3.2 使用shell脚本向python脚本内的方法传递参数
python脚本如下:(py_test.py)1
2
3
4
5def fun1():
return "无参数方法fun1"
def fun2(x):
return f"有参数方法fun2且传入的参数为{x}"
3.2.1 (1)无参数调用:
文件名:py_test_shell.sh1
2
3
#定义变量
python -c 'import python_test;print(python_test.fun1())'
sh py_test_shell.sh
输出:1
无参数方法fun1
3.2.2 (2)有参数调用:
文件名:py_test_shell.sh1
2
3
4#!/bin/bash
#定义变量
para=$1
python -c "import python_test;print(python_test.fun2('${para}'))"
执行命令:sh py_test_shell.sh hello
输出:有参数方法fun2且传入的参数为hello
3.2.3 (3)一次调用所有方法,放入一个集合中,再调用切割方法获取相应的值
1 | !/bin/bash |
输出:1
2fun1方法的返回结果为:无参数方法fun1
fun2方法的返回结果为:有参数方法fun2且传入的参数为helloworld
参考文章:参考文章