Python 简明教程
Python - Command-Line Arguments
Python Command Line Arguments
Python 命令行参数提供了一种便利的方式,可以在运行程序时在命令行中接受一些信息。我们通常将这些值与 Python 脚本的名称一起传递。
Python Command Line Arguments provides a convenient way to accept some information at the command line while running the program. We usually pass these values along with the name of the Python script.
要运行 Python 程序,我们在操作系统的命令提示符终端中执行以下命令。例如,在 Windows 中,在 Windows 命令提示符终端中输入以下命令。
To run a Python program, we execute the following command in the command prompt terminal of the operating system. For example, in windows, the following command is entered in Windows command prompt terminal.
$ python script.py arg1 arg2 arg3
此处的 Python 脚本名称为 script.py ,其余三个参数 - arg1 arg2 arg3 是程序的命令行参数。
Here Python script name is script.py and rest of the three arguments - arg1 arg2 arg3 are command line arguments for the program.
如果程序需要接受用户的输入,则使用 Python 的 input() 函数。当从命令行执行程序时,会从命令终端接受用户输入。
If the program needs to accept input from the user, Python’s input() function is used. When the program is executed from command line, user input is accepted from the command terminal.
Passing Arguments at the Time of Execution
非常频繁地,你可能需要将程序使用的数据放到命令行中,并在程序内部使用它。在命令行中提供数据的示例可能是 Windows 或 Linux 中的任何 DOS 命令。
Very often, you may need to put the data to be used by the program in the command line itself and use it inside the program. An example of giving the data in the command line could be any DOS commands in Windows or Linux.
在 Windows 中,使用下面的 DOS 命令将文件 hello.py 重命名为 hi.py:
In Windows, you use the following DOS command to rename a file hello.py to hi.py.
C:\Python311>ren hello.py hi.py
在 Linux 中可能使用 mv 命令:
In Linux you may use the mv command −
$ mv hello.py hi.py
此处 ren 或 mv 是需要旧文件和新文件名的命令。由于这些命令与命令行一致,因此它们被称为命令行参数。
Here ren or mv are the commands which need the old and new file names. Since they are put in line with the command, they are called command-line arguments.
可以从命令行将值传递到 Python 程序。Python 以列表对象收集参数。Python 的 sys 模块通过 sys.argv 变量访问所有命令行参数。sys.argv 是命令行参数列表,sys.argv[0] 是程序,即脚本名称。
You can pass values to a Python program from command line. Python collects the arguments in a list object. Python’s sys module provides access to any command-line arguments via the sys.argv variable. sys.argv is the list of command-line arguments and sys.argv[0] is the program i.e. the script name.
Example
hello.py 脚本在脚本运行后使用 input() 函数来接受用户输入。让我们更改它来接受命令行的输入。
The hello.py script used input() function to accept user input after the script is run. Let us change it to accept input from command line.
import sys
print ('argument list', sys.argv)
name = sys.argv[1]
print ("Hello {}. How are you?".format(name))
按照以下图片中的所示从命令行运行该程序:
Run the program from command-line as shown in the following figure −
output 如下所示:
The output is shown below −
C:\Python311>python hello.py Rajan
argument list ['hello.py', 'Rajan']
Hello Rajan. How are you?
命令行参数始终存储在字符串变量中。要将它们用作数字,可以用数字转换函数适当转换它们。
The command-line arguments are always stored in string variables. To use them as numerics, you can them suitably with type conversion functions.
Example
在下面的示例中,两个数字作为命令行参数被输入。在程序内部,使用 int() 函数将它们解析为整数变量。
In the following example, two numbers are entered as command-line arguments. Inside the program, we use int() function to parse them as integer variables.
import sys
print ('argument list', sys.argv)
first = int(sys.argv[1])
second = int(sys.argv[2])
print ("sum = {}".format(first+second))
它将生成以下 output −
It will produce the following output −
C:\Python311>python hello.py 10 20
argument list ['hello.py', '10', '20']
sum = 30
Python 的标准库包括几个有用的模块来解析命令行参数和选项:
Python’s standard library includes a couple of useful modules to parse command line arguments and options −
-
getopt − C-style parser for command line options.
-
argparse − Parser for command-line options, arguments and sub-commands.
Python getopt Module
Python 提供 getopt 模块来帮助你解析命令行选项和参数。此模块提供两个函数和一个异常以启用命令行参数的解析。
Python provides a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command line argument parsing.
getopt.getopt() method
此方法解析命令行选项和参数列表。以下是该方法的简单语法:
This method parses the command line options and parameter list. Following is a simple syntax for this method −
getopt.getopt(args, options, [long_options])
以下是参数的说明:
Here is the detail of the parameters −
-
args − This is the argument list to be parsed.
-
options − This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).
-
long_options − This is an optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign ('='). To accept only long options, options should be an empty string.
此方法返回由两个元素组成的值,第一个元素是 (选项,值) 对的列表,第二个元素是在选项列表被剥离后的剩余程序参数的列表。
This method returns a value consisting of two elements − the first is a list of (option, value) pairs, the second is a list of program arguments left after the option list was stripped.
返回的每个选项和值对将选项作为其第一个元素,短选项前面带有连字符(例如,'-x'),长选项前面带有两个连字符(例如,'--long-option')。
Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option').
Exception getopt.GetoptError
当在参数列表中找到未识别的选项,或当需要参数的选项没有提供任何参数时,就会引发这种情况。
This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none.
异常的参数是一个字符串,表示错误的原因。msg 和 opt 属性给出了错误消息和相关选项。
The argument to the exception is a string indicating the cause of the error. The attributes msg and opt give the error message and related option.
假设我们要通过命令行传递两个文件名,我们还希望提供一个选项来检查脚本的使用情况。脚本的使用方式如下:
Suppose we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows −
usage: test.py -i <inputfile> -o <outputfile>
下面是 test.py 的测试脚本:
Here is the following script to test.py −
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])
现在,运行上面的脚本,如下所示:
Now, run the above script as follows −
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile -o outputfile
Input file is " inputfile
Output file is " outputfile
Python argparse Module
argparse 模块提供编写非常易于使用的命令行界面的工具。它处理如何解析在 sys.argv 列表中收集的参数,在给出无效选项时自动生成帮助并发出错误消息。
The argparse module provides tools for writing very easy to use command line interfaces. It handles how to parse the arguments collected in sys.argv list, automatically generate help and issues error message when invalid options are given.
设计命令行界面的第一步是设置解析器对象。这可以通过 argparse 模块中的 ArgumentParser() 函数完成。可以将解释性字符串作为 description 参数提供给该函数。
First step to design the command line interface is to set up parser object. This is done by ArgumentParser() function in argparse module. The function can be given an explanatory string as description parameter.
首先,我们的脚本将从命令行中执行,没有任何参数。仍然使用解析器对象的 parse_args() 方法,这样做不会执行任何操作,因为没有给定任何参数。
To start with our script will be executed from command line without any arguments. Still use parse_args() method of parser object, which does nothing because there aren’t any arguments given.
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
args=parser.parse_args()
当运行上面的脚本时:
When the above script is run −
C:\Python311>python parser1.py
C:\Python311>python parser1.py -h
usage: parser1.py [-h]
sample argument parser
options:
-h, --help show this help message and exit
第二个命令行用法给出了 −help 选项,它生成所示的帮助消息。 −help 参数默认可用。
The second command line usage gives −help option which produces a help message as shown. The −help parameter is available by default.
现在让我们定义一个对脚本运行必不可少的参数,如果未给出,脚本应该抛出错误。这里我们通过 add_argument() 方法定义参数 'user'。
Now let us define an argument which is mandatory for the script to run and if not given script should throw error. Here we define argument 'user' by add_argument() method.
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user")
args=parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")
此脚本的帮助现在显示了一个位置参数,形式为 'user'。程序检查其值是否为 'Admin',并打印相应的消息。
This script’s help now shows one positional argument in the form of 'user'. The program checks if it’s value is 'Admin' or not and prints corresponding message.
C:\Python311>python parser2.py --help
usage: parser2.py [-h] user
sample argument parser
positional arguments:
user
options:
-h, --help show this help message and exit
使用以下命令:
Use the following command −
C:\Python311>python parser2.py Admin
Hello Admin
但以下用法显示了 Hello Guest 消息。
But the following usage displays Hello Guest message.
C:\Python311>python parser2.py Rajan
Hello Guest
The add_argument() method
我们可以在 add_argument() 方法中为参数分配默认值。
We can assign default value to an argument in add_argument() method.
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user", nargs='?',default="Admin")
args=parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")
这里的 nargs 是应该使用的命令行参数的数量。'?'。在可能的情况下,将从命令行消耗一个参数,并作为单个项目生成。如果不存在命令行参数,将生成 default 中的值。
Here nargs is the number of command-line arguments that should be consumed. '?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced.
默认情况下,所有参数都被视为字符串。若要明确指定参数类型,请在 add_argument() 方法中使用类型参数。所有 Python 数据类型都为 type 的有效值。
By default, all arguments are treated as strings. To explicitly mention type of argument, use type parameter in the add_argument() method. All Python data types are valid values of type.
import argparse
parser=argparse.ArgumentParser(description="add numbers")
parser.add_argument("first", type=int)
parser.add_argument("second", type=int)
args=parser.parse_args()
x=args.first
y=args.second
z=x+y
print ('addition of {} and {} = {}'.format(x,y,z))
它将生成以下 output −
It will produce the following output −
C:\Python311>python parser3.py 10 20
addition of 10 and 20 = 30
在上面的示例中,参数是必需的。要添加可选参数,请在其名称前加上双破折号 --。在以下情况下,surname 参数是可选的,因为它之前带有双破折号 (--surname)。
In the above examples, the arguments are mandatory. To add optional argument, prefix its name by double dash --. In following case surname argument is optional because it is prefixed by double dash (--surname).
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--surname")
args=parser.parse_args()
print ("My name is ", args.name, end=' ')
if args.surname:
print (args.surname)
以单个破折号做前缀,一个字母名称的参数充当短名称选项。
A one letter name of argument prefixed by single dash acts as a short name option.
C:\Python311>python parser3.py Anup
My name is Anup
C:\Python311>python parser3.py Anup --surname Gupta
My name is Anup Gupta
如果希望参数仅在定义的列表中取值,那么可以将它定义为 choices 参数。
If it is desired that an argument should value only from a defined list, it is defined as choices parameter.
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("sub", choices=['Physics', 'Maths', 'Biology'])
args=parser.parse_args()
print ("My subject is ", args.sub)
请注意,如果参数的值不在列表中,则会显示无效选项错误。
Note that if value of parameter is not from the list, invalid choice error is displayed.
C:\Python311>python parser3.py Physics
My subject is Physics
C:\Python311>python parser3.py History
usage: parser3.py [-h] {Physics,Maths,Biology}
parser3.py: error: argument sub: invalid choice: 'History' (choose from
'Physics', 'Maths', 'Biology')