在本课中,我们将学习在命令行中使用参数的几种方法,以及如何操纵它们在我们预先写好的Python脚本中运行。
我们将探索和比较的三种方法是:
sys.argvargparsegetopt
这些方法是按照易用性和简单性排序的。
我已经添加了 getopt() 方法用于演示,并把它放在最后,因为我发现它是三个方法中最没用的--你可能有不同的看法,所以看看它并做出你自己的结论。
方法 1- sys.argv
首先,我们将需要导入 [sys](https://blog.finxter.com/how-to-execute-system-commands-with-python/)模块--"系统特定参数和函数"。
argv 代表的是 "参数向量",基本上是一个变量,包含通过命令行传递的参数。
我的脚本使用VScode文本编辑器,你可以在文件路径中看到,然后在实际的文件名和参数前跟着调用 "Python"。 这在每个方法中都将是一样的。
你可以简写为 Python为 py如果你想节省输入的时间,可以在vscode之后缩写为 ,这样就可以了。
import sys
print('What is the name of the script?', sys.argv[0])
print('How many arguments?', len(sys.argv))
print('What are the arguments?', str(sys.argv))
# Adding arguments on command line
(base) PS C:\Users\tberr\.vscode> python test_command.py 3 4 5 6
输出
What is the name of the Script? test_command.py
How many arguments? 5
What are the arguments? ['test_command.py', '3', '4', '5', '6']
我们可以看到,文件名是位于[0] 索引位置的第一个参数,四个整数位于我们的字符串列表中的index[1:] (1,2,3,4)。
现在让我们来做一些比较有意义的代码。
用命令行上输入的数字进行加法的简单脚本。
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module (we will talk about argparse next)
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
用命令行上输入的参数进行输出。
(base) PS C:\Users\tberr\.vscode> python test_command.py 4 5 7 8
Total arguments passed: 5
Name of Python script: test_command.py
Arguments passed: 4 5 7 8
Result: 24
这给用户提供了通过的总参数,脚本的名称,通过的参数(不包括脚本名称),以及整数的 "和"。 现在让我们来看看argparse 方法。
注意:如果你在命令行上传递参数时得到一个 "错误 "或与预期不同的结果,请确保你所调用的文件已经被保存。 如果你的Python文件已经被修改或者是新的,那么在你这样做之前,它将无法工作。
方法2 - argparse
用于命令行选项、参数和子命令的解析器。
argparse 推荐使用argparse而不是 ,因为它更简单,使用的代码行数更少。getopt
代码。
import argparse
# Initialize the parser
parser = argparse.ArgumentParser(description = 'process some integers.')
# Adding Arguments
parser.add_arguments('integers', metavar = 'N',
type = int, nargs = '+',
help = 'an integer for the accumulator')
parser.add_arguments(dest = 'accumulate',
action = 'store_const",
const = sum,
help = 'sum the integers')
args = parser.parse_args()
print(args.accumulate(args.integers))
我们看到,首先,我们初始化解析器,然后用代码的'parser.add_arguments'部分添加参数。
我们还添加了一些帮助信息,以指导用户了解脚本正在发生的事情。 当我们在命令行上输入参数并看到我们的输出时,这将非常清楚。
输出
# Add arguments on the command line. -h (for help) and four integers
(base) PS C:\Users\tberr\.vscode> python argparse.py -h 5 3 6 7
usage: argparse.py [-h] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
accumulate sum the integers
optional arguments:
-h, – help show this help message and exit # Run code again without the help argument, just sum the integers.
(base) PS C:\Users\tberr\.vscode> python argParse.py 5 3 6 7
21
这是一种在命令行上传递参数的极好的、干净的方法,增加'help'参数可以使用户非常清楚。
方法3 - getopt
一种解析命令行选项和参数的方法,非常类似于C语言中的getopt() 函数。 这是一些基本代码,用于获取命令行上的用户名称。
代码。
import sys
import getopt
def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:")
except:
print("Error")
for opt, arg in opts:
if opt in ['-f']:
first_name = arg
elif opt in ['-l']:
last_name = arg
print( first_name +" " + last_name)
full_name()
我们设置了参数 'f' 和 'l' 作为名字和姓氏,并将它们传入命令行参数。
在命令行中输出。
(base) PS C:\Users\tberr\.vscode> py getOpt.py -f Tony -l Berry
Tony Berry
为了得到‘Full Name'这样一个简单的结果,这当然是大量的代码,这也是我喜欢sys.argv 和argparse 模块而不是getopt 的原因。 这并不意味着你在getopt 模块中找不到一些价值,这只是我的偏好。
总结
这些都是强大的Python工具,当用户想与你的代码进行交互时,它们会很有帮助,并且可以使这个过程变得简单而清晰。
我们在这里已经涵盖了基础知识,让你开始学习,并让你对Python的一些内置模块有一个概念。