美文网首页
python 脚本参数的传递

python 脚本参数的传递

作者: tafanfly | 来源:发表于2019-07-04 10:24 被阅读0次

1.sys.argv
2.getopt
3.argparse

注意: 不能在python IDE上调试

sys.argv

sys.argv 是从外部获取输入的参数,返回的是一个列表list, 第一个参数是脚本的名字, 后面的是依次输入的参数,适合一些简单参数输入的情形。

import sys

if __name__ == '__main__':
    print (sys.argv)

# testing result
python transmit.py name age job
['transmit.py', 'name', 'age', 'job']

getopt

该模块是专门用来处理命令行参数的
函数:opts, args = getopt(args, shortopts, longopts = [])
参数:

  • args: 一般是sys.argv[1:]
  • shortopts: 短格式 (-) , 只表示开关状态时,即后面不带附加数值时,在分析串中写入选项字符。当选项后面要带一个附加数值时,在分析串中写入选项字符同时后面加一个:号 , 如"vc:"。
  • longopts:长格式(--) , 只表示开关状态时,即后面不带附加数值时,在队列中写入选项字符。当选项后面要带一个附加数值时,在队列中写入选项字符同时后面加一个=号 , 如["help", "log="] 。

返回:

  • opts: 分析出的格式信息,是一个两元组的列表,即[(选项串1, 附加参数1), (选项串2, '')], 注意如果没有附加数值则为空字符串
  • args: 为不属于格式信息的剩余的命令行参数
import sys
import getopt


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hi:', ['help', 'input='])
        print (opts, args)
    except getopt.GetoptError as e:
        print ('Got a eror and exit, error is %s' % str(e))

测试结果如下:

  • 不传任何参数, 返回两个空的list
$ python getopt_test.py
[] []
  • 不传带---的参数, opts是空的列表,args是两个入参的列表
$ python getopt_test.py value1 value2
[] ['value1', 'value2']
  • 输入含有-h的参数, 可以得知h后不接:, 表明-h不会去取值
$ python getopt_test.py -h
[('-h', '')] []
$ python getopt_test.py -h 1
[('-h', '')] ['1']
$ python getopt_test.py -h -p
Got a eror and exit, error is option -p not recognized
  • 输入含有-i的参数, 可以得知i后接:, 表明-i一定会去取值
$ python getopt_test.py -i
Got a eror and exit, error is option -i requires argument
$ python getopt_test.py -i 1
[('-i', '1')] []
$ python getopt_test.py -i -p
[('-i', '-p')] []
  • 输入其他带有-的参数, 会直接报错,不认识这个参数
$ python getopt_test.py -a
Got a eror and exit, error is option -a not recognized
  • 输入带有--的参数, 和带-的参数类似, 如果后面不接=,则表示不需要取值, 后面接了=, 则表示一定要取值。
$ python getopt_test.py --help
[('--help', '')] []

$ python getopt_test.py --help 1
[('--help', '')] ['1']

$ python getopt_test.py --help --ls
Got a eror and exit, error is option --ls not recognized

$ python getopt_test.py --help --input
Got a eror and exit, error is option --input requires argument

$ python getopt_test.py --help --input 2
[('--help', ''), ('--input', '2')] []

$ python getopt_test.py --help --input 2 3
[('--help', ''), ('--input', '2')] ['3']
  • 输入全体参数
$ python getopt_test.py -h -i 1 --help --input 2 3
[('-h', ''), ('-i', '1'), ('--help', ''), ('--input', '2')] ['3']

argparse

argparse 模块可被用来解析命令行选项。
add_argument() 方法定义

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

1. name or flags - 选项字符串的名字或者列表,例如 foo 或者 -f, --foo
2. action - 命令行遇到参数时的动作,默认值是 store
    2.1 store_const,表示赋值为const
    2.2 append,将遇到的值存储成列表,也就是如果参数重复则会保存多个值
    2.3 append_const,将参数规范中定义的一个值保存到一个列表
    2.4 count,存储遇到的次数;此外,也可以继承 argparse.Action 自定义参数解析
3. nargs - 应该读取的命令行参数个数,可以是具体的数字,或者是?号,当不指定值时对于 Positional argument 使用 default,对于 Optional argument 使用 const;或者是 * 号,表示 0 或多个参数;或者是 + 号表示 1 或多个参数
4. const - action 和 nargs 所需要的常量值
5. default - 不指定参数时的默认值
6. type - 命令行参数应该被转换成的类型。
7. choices - 参数可允许的值的一个容器
8. required - 可选参数是否可以省略 (仅针对可选参数)
9. help - 参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息
10. metavar - 在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称
11. dest - 解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线

主要有三个步骤:

  1. 创建 ArgumentParser() 对象
  2. 调用 add_argument() 方法添加参数
  3. 使用 parse_args() 解析添加的参数

实例分析:

import argparse

parser = argparse.ArgumentParser('description=Show the usage')
parser.add_argument('integer', type=int, help='display an integer')
args = parser.parse_args()

print (args.integer)

#result
$ python argparse_test.py -h
usage: description=Show the usage [-h] integer

positional arguments:
  integer     display an integer

optional arguments:
  -h, --help  show this help message and exit
--------------------------------------------------
$ python argparse_test.py 1
1

相关文章

  • 2021-09-10

    python调用shell脚本 1. 传入参数 python文件 可以套用python传递参数,二次传递给shel...

  • python脚本传递参数

    给python程序传递参数 运行python脚本时有时需要执行实传递参数 在linux下: [root@Test ...

  • 利用Python格式化文件

    利用Python 脚本 格式化文件,可传递两个传递参数 #!/usr/bin/env python #encodi...

  • python脚本传递参数

    执行脚本: 脚本内容: 输出结果:

  • python脚本传递参数

    脚本传递参数有好几种:sys.argv、argparse、 tf.app.run,这里介绍第一种: 在linux下...

  • 工具 | Shell 教程笔记 (2)

    Shell 传递参数 在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n 其他用法: 参考 ...

  • shell(三)

    Shell 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一...

  • shell中$0、$1、$n、$#、$*、$@的区别

    $0脚本名称 $1传递给脚本或者函数的第一个参数 $n传递给函数或者脚本的第n个参数 $#传递给函数或者脚本的参数...

  • Shell变量传递

    传递参数 在执行Shell脚本时,可以向脚本传递参数,脚本内获取参数的格式为:$n,n代表数字,指示执行脚本的第n...

  • Shell 传递参数

    Shell 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n代表一个...

网友评论

      本文标题:python 脚本参数的传递

      本文链接:https://www.haomeiwen.com/subject/xlvqwftx.html