跳轉中,訪問新網域網站 https://samiliu.xyz

logo头像
Snippet 博客主题

Python getopt 命令列參數

Python 提供 getopt 模組,提供幫助解析命令列的選項和參數。另外可以透過 sys.argv 取得命令列任何參數。


函數

getopt

解析命令列

getopt(argv, shortopts, longopts=[])
  • argv:要解析的參數,通常是sys.argv[1:]
  • shortopts:要識別的短格式(-),其有要求參數後須加:
  • longopts:可選,要識別的長格式(--),有參數要求加=

GetoptError

當再命令列發現未被辨識的選項,或需要被賦予參數得選項無參數時,將會發出異常。

try:
    ...
except getopt.GetoptError:
    ...

範例

程式範例

demo-getopt.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import getopt


def usage():
    print(f'''Usage:{sys.argv[0]} [-i name | --ifile=name][-o name | --ofile=name]
    -h help
    -i input file path
    -o output file path
    ''')


def main(argv):
    input_file = ''
    output_file = ''

    try:
        opts, args = getopt.getopt(argv[1:], 'hi:o:', ["help", "ifile=", "ofile="])
    except getopt.GetoptError:
        print(f'{argv[0]} -i <inputfile> -o <outputfile>')
        sys.exit()

    for name, value in opts:
        if name in ('-h', '--help'):
            usage()
            sys.exit()
        elif name in ('-i', '--ifile'):
            input_file = value
        elif name in ('-o', '--ofile'):
            output_file = value
    print(f'<<< Input file is {input_file} <<<')
    print(f'>>> Output file is {output_file} >>>')


if __name__ == '__main__':
    main(sys.argv)

演示結果

  1. python demo-getopt.py -h
    # Usage:demo-getopt.py [-i name | --ifile=name][-o name | --ofile=name]
    #    -h help
    #    -i input file path
    #    -o output file path
  2. python demo-getopt.py -i text.txt --ofile=data.csv
    # <<< Input file is text.txt <<<
    # >>> Output file is data.csv >>>