首页 > 编程知识 正文

python常用命令,python django

时间:2023-05-05 18:48:02 阅读:41327 作者:2557

Python命令行参数详细信息0 .命令行参数1.sys.argv2. getopt 2.1 getopt.getopt方法2.2 exception getopt.getopt error3. arg parse

0 .命令行参数

对于大型项目程序,运行程序通常需要执行的步骤之一是正确处理命令行参数,即提供给包含参数化信息的程序或脚本的参数。 例如,在计算机视觉项目中,与图像不同类型的文件通常作为命令行参数传递给脚本,以便程序可以处理不同的图像和不同类型的文件。

命令行参数是参数化程序执行的一种常见而简单的方法。 以下主要介绍如何获取和分析三个常用的命令行参数。

1 .为了处理sys.argv命令行参数,Python具有内置的sys.argv模块,您可以通过模块中的sys.argv访问所有命令行参数。 其返回值是包含所有命令行参数的列表(list )。 程序运行时,Python将从命令行获取所有值并将其存储在sys.argv列表中。 列表中的第一个元素sys.argv[0]是脚本的完整路径。 或者,脚本名称——取决于操作系统。 的第二个元素是脚本的第一个命令行参数,例如sys.argv[1]。 如下图所示,script_1.py脚本使用两个参数执行。

接下来,让我们来看看sys.argv是如何工作的。 首先,编写scripy_1.py脚本。

import sysprint ('正在运行的脚本名称:'{}'.format ) sys.argv[0] ) )脚本的参数数量:'{}'.format ) len ) sys.

python script_1.py显示以下信息:

正在运行的脚本名称3: 'script_1.py '脚本的参数数量: '1'脚本的参数: '['script_1.py'] '多个参数用于此脚本

python script _1. py opencv-itest.png提供以下信息:

正在运行的脚本名称: 'script_1.py '脚本的参数数量: '4'脚本的参数: '['script_1.py '、' OpenCV '、'-I ' ] 但是,由于sys.argv还将命令行选项-i作为参数进行识别,因此很难满足我们的需要,因此引入了getopt模块来识别命令行选项。

2. getopt getopt模块是一个专用于命令行参数的模块,用于获取命令行选项和参数。 命令行选项使程序参数更加灵活,并支持短选项模式(-)和长选项模式(-)。

此模块有两种用于分析命令行参数的方法和异常处理。

2.1 getopt.getopt方法getopt.getopt方法用于分析命令行参数列表,语法格式如下:

getopt.getopt(args,options[,long_options] )方法参数的说明如下表所示。

参数说明args解决的命令行参数的列表。 通常为sys.argv[1:],脚本名称(sys.argv[0] ) options必须以字符串格式定义。 options后的冒号" : "表示设置此选项时需要其他参数,否则long_options后的等号"="表示不添加参数lions 没有冒号表示没有将参数添加到选项中。 方法的返回值由两个元素组成。 最初,这是“选项,值”元组的列表。 第二个是参数列表,其中包含没有-或-的参数。

编写script_2.py脚本进行演示。

importsysimportgetoptdefmain (argv ) : input _ file=' ' output _ file=' ' # ' hi : o : ' 3360短格式分析列,在h之后表示后面有参数# ['help '、' input_file='、' output_file=']:长格式的分析字符串列表,help后面没有等号,后面没有参数input_file和output_file后面有冒号。 这表示后面有参数#。 返回值为` opts '和` args ',opts是以元组为元素的列表,每个元组的格式为: (可选,附加参数),例如:((-I )、) TT。# args为

g in opts: if opt in ("-h", "--help"): print('script_2.py -i <input_file> -o <output_file>') print('or: test_arg.py --input_file=<input_file> --output_file=<output_file>') sys.exit() elif opt in ("-i", "--input_file"): input_file = arg elif opt in ("-o", "--output_file"): output_file = arg print('输入文件为:', input_file) print('输出文件为:', output_file) # 打印不含'-'或'--'的参数 for i in range(0, len(args)): print('不含'-'或'--'的参数 %s 为:%s' % (i + 1, args[i])) if __name__ == "__main__": main(sys.argv)

使用带有命令行选项的命令执行此脚本,以下两种方式是等价的:

# 方式1python scripy_1.py -i test.png -o output.png OpenCV# 方式2python scripy_1.py --input_file test.png --output_file output.png OpenCV

输出得到以下信息:

输入文件为: test.png输出文件为: output.png不含'-'或'--'的参数 1 为:OpenCV 2.2 Exception getopt.GetoptError

在参数列表中没有找到所传递参数,或选项的需要的参数为空时会触发该异常。异常的参数是一个字符串,表示错误的原因。属性 msg 和 opt 为相关选项的错误信息。
在上述代码中添加异常处理,检查此错误信息:

# ...def main(argv): input_file = "" output_file = "" try: opts, args = getopt.getopt(argv[1:], "hi:o", ["help", "input_file=", "output_file="]) except getopt.GetoptError as e: print(e.msg) print(e.opt) sys.exit(2)# ...

使用错误的格式选项传递参数执行脚本:

python scripy_1.py -f

输出以下错误信息:

option -f not recognizedf 3. argparse

当程序中使用采用复杂参数或多个文件名时,推荐使用 Python 的 argparse 库,它以系统的方式处理命令行参数,从而可以编写用户友好的命令行程序。Python 标准库 argparse 同样也是用于解析命令行参数的模块。首先,由程序确定所需的参数,然后, argparse 将这些参数解析为 sys.argv。此外,argparse 会生成帮助和使用信息提示,并在提供无效参数时发出错误。
为了介绍此模块,编写 script_3.py,如下所示:

import argparseparser = argparse.ArgumentParser()parser.parse_args()

不带参数运行此脚本不会向 stdout 显示任何内容。但是,如果使用 --help 或 -h 选项,将得到脚本的使用信息提示:

usage: scripy_3.py [-h]optional arguments:-h, --help show this help message and exit

指定其他参数会导致错误,例如使用如下命令:

scripy_3.py -i

则会报导致错误:

usage: scripy_3.py [-h]argparse_minimal.py: error: unrecognized arguments: -i

由于未定义参数,因此不允许其他参数,接下来就添加一个参数,编写 script_4.py 脚本:

import argparseparser = argparse.ArgumentParser()parser.add_argument("first_argument", help="this is the string text in connection with first_argument")args = parser.parse_args()print(args.first_argument)

这里添加了 add_argument() 方法。此方法用于指定程序将接受哪些命令行选项,此处添加了 first_argument 参数。此外, argparse 模块存储所有参数,将其名称与每个添加参数的名称相匹配——在此处为 first_argument 。为了获得参数值,需要使用 args.first_argument。
如果此脚本以下示方法执行,则输出为 10:

python scripy_4.py 10

但如果脚本在没有参数的情况下执行,则将输出以下信息:

usage: scripy_4.py [-h] first_argumentscripy_4.py: error: the following arguments are required: first_argument

最后,如果我们使用 -h 选项执行脚本,输出将如下所示:

usage: scripy_4.py [-h] first_argumentpositional arguments: first_argument this is the string text in connection with first_argumentoptional arguments: -h, --help show this help message and exit

默认情况下,argparse 将提供的选项视为字符串。因此,如果参数不是字符串,则应使用 type 选项。使用 script_5.py 脚本,其中添加了两个参数,这两个参数是 int 类型:

import argparseparser = argparse.ArgumentParser()parser.add_argument("first_number", help="first number to be added", type=int)parser.add_argument("second_number", help="second number to be added", type=int)args = parser.parse_args()print("args: '{}'".format(args))print("the sum is: '{}'".format(args.first_number + args.second_number))args_dict = vars(parser.parse_args())print("args_dict dictionary: '{}'".format(args_dict))print("first argument from the dictionary: '{}'".format(args_dict["first_number"]))

在前面的示例中,通过调用 vars() 函数将参数存储在字典中:

args_dict = vars(parser.parse_args())print("args_dict dictionary: '{}'".format(args_dict))print("first argument from the dictionary: '{}'".format(args_dict["first_number"]))

如果不带参数执行脚本:

python script_5.py

则输出如下:

usage: scripy_5.py [-h] first_number second_numberscripy_5.py: error: the following arguments are required: first_number, second_number

此外,如果我们使用 -h 选项执行脚本:

python script_5.py --help

输出将如下所示:

usage: scripy_1.py [-h] first_number second_numberpositional arguments: first_number first number to be added second_number second number to be addedoptional arguments: -h, --help show this help message and exit

如果此脚本以如下方式执行:

python script_5.py 123 456

则输出如下:

args: 'Namespace(first_number=123, second_number=456)'the sum is: '579'args_dict dictionary: '{'first_number': 123, 'second_number': 456}'first argument from the dictionary: '123'

更多 argparse 的高级介绍可以在官方文档中看到,其中包括了大量示例。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。