Python命令列引數解析模組getopt使用例項

2021-09-27 06:12:23 字數 1716 閱讀 1962

這篇文章主要介紹了python命令列引數解析模組getopt使用例項,本文講解了使用語法格式、短選項引數例項、長選項引數例項等內容,需要的朋友可以參考下

格式

getopt(args, options[, long_options])

1.args表示要解析的引數.

2.options表示指令碼要識別的字元.字元之間用」:」分隔,而且必須要以」:」後結尾,例如」a?️c:」.

3.long_options是可選的,如果指定的話,可以解析長選項.形式為字串列表,如[『foo=』, 『frob=』].長選項要求形式為」–name=value」

4.該方法返回2個元素.第乙個元素是列表對, 對中第乙個值是帶有」-「或者」–」的選項名,第二個值是選項的值.第二個元素是options減去第乙個元素的後的值,即不能識別的值.

如果要求只能解析長選項的話,options必須為空.只要指定了引數名,就必須傳入引數,不支援可有可無的引數.

短選項例項

**如下:

'''

'''import getopt

short_args = '-a 123 -b boy -c foo -d 2.3 unkown'.split()

print short_args

optlist, args = getopt.getopt(short_args, 'a:b:c:d:')

print optlist

print args

輸出

**如下:

['-a', '123', '-b', 'boy', '-c', 'foo', '-d', '2.3', 'unkown']

[('-a', '123'), ('-b', 'boy'), ('-c', 'foo'), ('-d', '2.3')]

['unkown']

長選項例項

**如下:

import getopt

long_args = '--a=123 --b unkown'.split()

optlist, args = getopt.getopt(long_args, '', ['a=', 'b'])

print optlist

print args

輸出

**如下:

[('--a', '123'), ('--b', '')]

['unkown']

長短選項結合例項

**如下:

import getopt

s = '--condition=foo --testing --output-file abc.def -x a1 unknown'

args = s.split()

optlist, args = getopt.getopt(args, 'x:', ['condition=', 'output-file=', 'testing'])

print optlist

print args

輸出

**如下:

[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', 'a1')]

['unknown']

python解析命令列引數

使用乙個先進的模組名為argparse,跟unix程式的命令列引數很像。直接對code做個筆記 import sys import argparse def main args print first name directory s args.first name print first para...

解析命令列引數

include include include include int make argv const char astr,const char delimiters,char argvp void free argv char argvp int main int argc,char argv i...

Python的命令列引數解析

命令列引數解析在程式語言中基本都會碰到,python中內建了乙個用於命令項選項與引數解析的模組argparse。下面主要介紹兩種解析python命令列引數的方式。解析python中命令列引數的最傳統的方法是通過sys.argv。demo如下 usr env python python coding ...