Python 中的参数解析
每种编程语言都具有创建脚本并从终端运行或被其他程序调用的功能。在运行此类脚本时,我们通常需要传递脚本执行各种功能所需的参数。在本文中,我们将了解将参数传递到 Python 脚本的各种方法。
使用 sys.argv
这是一个内置模块,sys.argv 可以处理与脚本一起传递的参数。默认情况下,在 sys.argv[0] 中考虑的第一个参数是文件名。其余参数的索引为 1、2 等。在下面的示例中,我们将看到脚本如何使用传递给它的参数。
import sys
print(sys.argv[0])
print("Hello ",sys.argv[1],", welcome!")我们采取以下步骤运行上述脚本并获得以下结果
要运行上述代码,我们转到终端窗口并编写如下所示的命令。这里脚本的名称是 args_demo.py。我们将一个值为 Samantha 的参数传递给此脚本。
D:\Pythons\py3projects>python3 args_demo.py Samantha args_demo.py Hello Samantha welcome!
使用 getopt
这是另一种方法,与前一种方法相比,它具有更大的灵活性。在这里,我们可以收集参数的值并与错误处理和异常一起处理它们。在下面的程序中,我们通过获取参数并跳过第一个参数(即文件名)来找到两个数字的乘积。当然,这里也使用了 sys 模块。
示例
import getopt
import sys
# Remove the first argument( the filename)
all_args = sys.argv[1:]
prod = 1
try:
# Gather the arguments
opts, arg = getopt.getopt(all_args, 'x:y:')
# Should have exactly two options
if len(opts) != 2:
print ('usage: args_demo.py -x <first_value> -b <second_value>')
else:
# Iterate over the options and values
for opt, arg_val in opts:
prod *= int(arg_val)
print('Product of the two numbers is {}'.format(prod))
except getopt.GetoptError:
print ('usage: args_demo.py -a <first_value> -b <second_value>')
sys.exit(2)输出
运行上述代码将得到以下结果:
D:\Pythons\py3projects >python3 args_demo.py -x 3 -y 12 Product of the two numbers is 36 # Next Run D:\Pythons\py3projects >python3 args_demo.py usage: args_demo.py -x <first_value> -b <second_value>
使用 argparse
这实际上是最常用的处理参数传递的模块,因为错误和异常由模块本身处理,无需额外的代码行。我们必须为将要使用的每个参数提及名称和帮助文本,然后在代码的其他部分使用参数的名称。
示例
import argparse
# Construct an argument parser
all_args = argparse.ArgumentParser()
# Add arguments to the parser
all_args.add_argument("-x", "--Value1", required=True,
help="first Value")
all_args.add_argument("-y", "--Value2", required=True,
help="second Value")
args = vars(all_args.parse_args())
# Find the product
print("Product is {}".format(int(args['Value1']) * int(args['Value2'])))输出
运行上述代码将得到以下结果:
D:\Pythons\py3projects>python3 args_demo.py -x 3 -y 21 Product is 63 # Next Run D:\Pythons\py3projects>python3 args_demo.py -x 3 -y usage: args_demo.py [-h] -x VALUE1 -y VALUE2 args_demo.py: error: argument -y/--Value2: expected one argument
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP