python命令列選項和引數分割

2021-07-07 06:59:18 字數 3592 閱讀 6822

python中使用getopt處理命令列引數,本文主要對getopt進行介紹。getopt的呼叫主要分三步:

1、匯入sys和getopt模組;

2、分析命令列引數;

3、處理結果;

第一步很簡單,只需要:

import sys

import getopt

第二步處理方法如下:

try:

opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="])

except getopt.getopterror:

# print help information and exit:

1. 處理所使用的函式叫getopt() ,因為是直接使用import 匯入的getopt 模組,所以要加上限定getopt 才可以。

2. 使用sys.argv[1:] 過濾掉第乙個引數(它是執行指令碼的名字,不應算作引數的一部分)。

3. 使用短格式分析串"ho:" 。當乙個選項只是表示開關狀態時,即後面不帶附加引數時,在分析串中寫入選項字元。當選項後面是帶乙個附加引數時,在分析串中寫入選項字元同時後面加乙個":" 號 。所以"ho:" 就表示"h" 是乙個開關選項;"o:" 則表示後面應該帶乙個引數。

4. 使用長格式分析串列表:["help", "output="] 。長格式串也可以有開關狀態,即後面不跟"=" 號。如果跟乙個等號則表示後面還應有乙個引數 。這個長格式表示"help" 是乙個開關選項;"output=" 則表示後面應該帶乙個引數。

5. 呼叫getopt 函式。函式返回兩個列表:opts 和args 。opts 為分析出的格式資訊。args 為不屬於格式資訊的剩餘的命令列引數。opts 是乙個兩元組的列表。每個元素為:( 選項串, 附加引數) 。如果沒有附加引數則為空串'' 。

6. 整個過程使用異常來包含,這樣當分析出錯時,就可以列印出使用資訊來通知使用者如何使用這個程式。

如上面解釋的乙個命令列例子為:

'-h -o file --help --output=out file1 file2'

在分析完成後,opts 應該是:

[('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')]

而args 則為:

['file1', 'file2']

第三步主要是對分析出的引數進行判斷,並進行下一步的處理。主要處理模式如下:

for o, a in opts:

if o in ("-h", "--help"):

usage()

sys.exit()

if o in ("-o", "--output"):

output = a

使用乙個迴圈,每次從opts 中取出乙個兩元組,賦給兩個變數。o 儲存選項引數,a 為附加引數。接著對取出的選項引數進行處理。

實踐篇1:

#!/usr/bin/env python

import sys;

import getopt;

def usage():

print("usage:%s [-a|-o|-c] [--help|--output] args...." %dsys.argv[0]);

if "__main__" == __name__:

#lsargs = [""];

try:

opts,args = getopt.getopt(sys.argv[1:], "ao:c", ["help", "output="]);

print("**********== opts ***************===");

print(opts);

print("**********== args ***************===");

print(args);

#check all param

for opt,arg in opts:

if opt in ("-h", "--help"):

usage();

sys.exit(1);

elif opt in ("-t", "--test"):

print("for test option");

else:

print("%s ==> %s" %(opt, arg));

except getopt.getopterror:

print("getopt error!");

usage();

sys.exit(1);

執行結果:

$ ./test_getopt.py  -a -oaaa -caa --output=out file1 t file2 -d

**********== opts ***************===

[('-a', ''), ('-o', 'aaa'), ('-c', ''), ('-a', ''), ('-a', ''), ('--output', 'out')]

**********== args ***************===

['file1', 't', 'file2', '-d']

-a ==>

-o ==> aaa

-c ==>

-a ==>

-a ==>

--output ==> out

實踐篇2:

import sys, getopt

def usage():

print \

'''usage:convert.py [<-i input_file>

<-o output_file>

[-h or --help]

]options:

-i: input_file

-o: output_file

-h or --help: help

example:convert.py -i test1 -o test2

'''shortargs = 'hi:o:'

longargs = 'help'

opts, args = getopt.getopt(sys.argv[1:], shortargs,[longargs])

print opts

print args

input_file = ''

output_file = ''

for op , value in opts:

if op == '-i':

input_file = value

elif op == '-o':

output_file = value

elif op in ('-h','--help'):

usage()

sys.exit()

本實踐中,定義shortargs時,有多個引數,假如後面沒有longargs,「o」後面的":"必須帶上,表示其為opts,而不是args;

C 命令列引數分析

include include intgetopt intargc,char const argv,const char optstring 選項字串為 of h p o表示是無引數選項 f p都為有引數選項 h 後面可以跟引數或者不跟 此函式影響的全域性變數有四個 extern char opta...

Linux 命令列引數分析

在實際程式之中我們經常要對命令列引數進行分析.比如我們有乙個程式a可以接受許多引數.乙個可能的情況是 a d print option1 hello option2 world 那麼我們如何對這個命令的引數進行分析了?經常用函式是getopt和getopt long.include include ...

boost 處理命令列選項引數

genmac.cpp 定義控制台應用程式的入口點。define crtdbg map alloc include include include stdafx.h include include include include include include include using namesp...