Python 中的参数解析

pythonserver side programmingprogramming更新于 2025/10/11 0:44:17

每种编程语言都具有创建脚本并从终端运行或由其他程序调用的功能。运行此类脚本时,我们经常需要传递脚本所需的参数,以便在脚本内执行各种函数。在本文中,我们将了解将参数传递到 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

# 构造参数解析器
all_args = argparse.ArgumentParser()

# 向解析器添加参数
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())

# 查找产品
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

相关文章


有用资源