Python命令行參數argv和argparse使用總結


概述

運行python腳本時通過命令行方式傳入運行參數通常有以下兩種自建方式:

  • sys.argv - 簡潔
  • argparse - 豐富,可自定義

下面詳細說一下具體時使用

argv

# test_argv.py

import sys

args = sys.argv
print(f'args = {args}')

>>> output
➜ git:(master) python3 test_argv.py         
args = ['test_argv.py']
➜ git:(master) ✗ python3 test_argv.py 1 2 3
args = ['test_argv.py', '1', '2', '3']
➜ git:(master) ✗ python3 test_argv.py 1 2 3 'hello world !'
args = ['test_argv.py', '1', '2', '3', 'hello world !']

從上面可以看出,通過argv方法獲取的結果:

  • 返回為list
  • 第一個參數為腳本本身
  • 如參數中間帶空格,用引號即可

argparse

argparse模塊的功能較為豐富,其核心是通過add_argument方法自定義入參的:標志、格式、類型和范圍等特性,常用如下:

  • *name_or_flag - 定義入參名或flag,如'-n', '--number'
  • type - 指定入參類型
  • choices - 指定入參范圍
  • default - 指定入參默認值
  • required - 指定該餐素是否不要,布爾類型
  • help - 參數概述

更多請參考: argparse

實例

test_argv.py

import argparse

# 初始化一個parser對象
parser = argparse.ArgumentParser(description='test module of argparse')

# 指定-n/--number的參數
# 類型為int
# help為簡短地說明
parser.add_argument(
    '-n', '--number', type=int,
    help='args of number'
)

# 指定-o/--output參數
# 並限制類型為:['txt', 'csv', 'doc']
parser.add_argument(
    '-o', '--output', type=str,
    choices=['txt', 'csv', 'doc'],
    help='output method'
)

# 指定-d/--default參數
# 並限制類型為:['txt', 'csv', 'doc']
parser.add_argument(
    '-d', '--default', type=int,
    choices=[_ for _ in range(1, 10)],
    default=5,
    help='default'
)

# 指定位置參數foo
parser.add_argument('foo')

args = parser.parse_args()
print(f'args = {args}')

# 獲取指定參數
print(
    f'number = {args.number}, type = {type(args.number)}\n'
    f'output = {args.output}, type = {type(args.output)}\n'
    f'default = {args.default}, type = {type(args.default)}\n'
    f'foo = {args.foo}, type = {type(args.foo)}'
)

output

# -h - 打印help
➜ git:(master) ✗ python3 test_argv.py -h
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
                    [-d {1,2,3,4,5,6,7,8,9}]
                    foo

test module of argparse

positional arguments:
  foo

optional arguments:
  -h, --help            show this help message and exit
  -n NUMBER, --number NUMBER
                        args of number
  -o {txt,csv,doc}, --output {txt,csv,doc}
                        output method
  -d {1,2,3,4,5,6,7,8,9}, --default {1,2,3,4,5,6,7,8,9}
                        default
# 不帶參數運行,結果為None
➜ git:(master) ✗ python3 test_argv.py   
args = Namespace(number=None, output=None)
number = None
output = None

# 帶參數運行
➜ git:(master) ✗ python3 test_argv.py -n 33 --output txt
args = Namespace(number=33, output='txt')
number = 33, type = <class 'int'>
output = txt, type = <class 'str'>

# 參數格式錯誤
➜ git:(master) ✗ python3 test_argv.py -n str         
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -n/--number: invalid int value: 'str'
➜ git:(master) ✗ python3 test_argv.py -o excel       
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -o/--output: invalid choice: 'excel' (choose from 'txt', 'csv', 'doc')

# 默認參數 
➜ git:(master) ✗ python3 test_argv.py      
args = Namespace(default=5, number=None, output=None)
number = None, type = <class 'NoneType'>
output = None, type = <class 'NoneType'>
output = 5, type = <class 'int'>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM