程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python add command line arguments

編輯:Python

攜手創作,共同成長!這是我參與「掘金日新計劃 · 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.

General steps for adding command line arguments

in the program script, argparse The basic usage can be shown in three steps:

  • Defines the arguments to be accepted by the script,Generate a new parameter parser
  • Call the defined parser,Returns an object containing all result parameters
  • The script is invoked with a command with parameters,Makes the defined parameter behavior take effect

一般而言,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 scripts
  • 為了清楚起見,Default values ​​should always be defined for optional parameters.Default value if not explicitly defined,則默認為 None,But this can be confusing to users
  • 同時,It should always be used when adding command line arguments add_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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved