攜手創作,共同成長!這是我參與「掘金日新計劃 · 8 月更文挑戰」的第8天,點擊查看活動詳情
Many task programs if structured as a command line interface for it,You can change the way it works by accepting different parameters.例如,在爬蟲程序中,不同 URL
Usually can be passed as a command line argument to the task program,Thereby, data from different web pages can be crawled.在 Python
The standard library contains a powerful one argparse
模塊,Rich command-line argument parsing can be easily created.
in the program script, argparse
The basic usage can be shown in three steps:
一般而言,Scripts using command line arguments follow the following structure:
導入相關庫
定義函數
定義參數解析器
對參數進行操作
Call the function with arguments,to perform different operations
復制代碼
其中,一般使用 main
function to explicitly declare the execution entry of the code,簡單情況下,We can directly use the parameters passed in the command line without complicated processing.
接下來,Let's walk through an example to see how to add and use command line arguments.首先創建一個腳本 argparse_example.py
,The script accepts a single integer as a positional argument,and print the number of executions “Hello world.
”.腳本代碼如下,We follow the above structure,其中定義的 main
Only execute the print function:
import argparse
def main(num):
print('Hello world.\n' * num)
if __name__ == '__main__':
parse = argparse.ArgumentParser()
parse.add_argument('number', type=int, help='A number')
args = parse.parse_args()
main(args.number)
復制代碼
在腳本中,參數通過 add_arguments
add to parser.After all parameters are defined,調用 parse_args()
Will return an object containing the result of parameter parsing,Exit execution if an error occurs.
Call the script and check how the parameters are used,Help is displayed automatically when the script is called without arguments,使用參數 -h
Extended help information can be displayed:
$ python argparse_example.py
usage: argparse_example.py [-h] number
argparse_example.py: error: the following arguments are required: number
$ python argparse_example.py -h
usage: argparse_example.py [-h] number
positional arguments:
number A number
optional arguments:
-h, --help show this help message and exit
復制代碼
Call the script with extra arguments,Scripts can be executed as expected by the program:
$ python argparse_example.py 3
Hello world.
Hello world.
Hello world.
$ python argparse_example.py three
usage: argparse_example.py [-h] number
argparse_example.py: error: argument number: invalid int value: 'three'
復制代碼
更改腳本,Add optional parameter to accept the string to be printed,且默認值為 “Hello world
”,編寫argparse_example_2.py
腳本如下所示:
import argparse
def main(string, num):
print(string * num)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('num', type=int, help='A number')
parser.add_argument('-s', type=str, help='String to print', default='Hello world.\n')
args = parser.parse_args()
main(args.s, args.num)
復制代碼
再次執行腳本,You can see that the help has been updated,使用 -s
Options can print different strings:
$ python argparse_example_2.py -h
usage: argparse_example_2.py [-h] [-s S] num
positional arguments:
num A number
optional arguments:
-h, --help show this help message and exit
-s S String to print
$ python argparse_example_2.py 3Hello world.
Hello world.
Hello world.
$ python argparse_example_2.py 3 -s 'I love movie'
I love movieI love movieI love movie
復制代碼
在實際場景中,We should add a help description for each parameter,Parameters can be divided into positional parameters and optional parameters,There is a big difference in how they are used:
-
開頭,treat it as an optional parameter,For example in a script -s
參數.否則,該參數為位置參數,Like numeric parameters in scriptsNone
,But this can be confusing to usersadd_agrment()
方法的 help
Parameters add help information with parameter descriptions,This is critical when calling the script,Can help users understand the meaning of each command line parameter