1. 程式人生 > >[Python小筆記]命令列引數:sys.argv和getopt模組

[Python小筆記]命令列引數:sys.argv和getopt模組

一、sys.argv

sys.argv 是命令列引數列表。

#test_sys_argv.py
import sys
print(sys.argv)#命令列引數列表
print(sys.argv[0])
print(len(sys.argv))#命令列引數列表個數

在這裡插入圖片描述

二、getopt模組

getopt模組是專門處理命令列引數的模組,用於獲取命令列選項和引數,也就是sys.argv。命令列選項使得程式的引數更加靈活。支援短選項模式(-)和長選項模式(–)。

該模組提供了兩個方法及一個異常處理來解析命令列引數。

getopt(args, shortopts, longopts=[])

getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means “sys.argv[1:]”. shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses). If
specified, longopts is a list of strings with the names of the
long options which should be supported. The leading ‘–’
characters should not be included in the option name. Options
which require an argument should be followed by an equal sign
(’=’).
The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument). Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
‘-x’), and the option argument as its second element, or an empty
string if the option has no argument. The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences. Long and short options may be mix

#test_getopt.py
import sys,getopt
try:
	options,args = getopt.getopt(sys.argv[1:],"hf:v:a:",["help","fruit=","vehicle=","annimal="])
except getopt.GetoptError:
	sys.exit()#退出主程式
print(options,args)
  • 適用於短格式的輸入:'hf:v:a:'
    h後面不帶冒號表示可以不帶引數,輸入引數的格式為:
    -h -f arg1 -v arg2 -a arg3
    在這裡插入圖片描述

  • 適用於短格式的輸入:['help','fruit=','vehicle=','annimal=']


    help後面不帶等號表示可以不帶引數,輸入引數的格式為:
    –help --fruit arg1 --vehicle arg2 --annimal arg3
    在這裡插入圖片描述

  • 也可以長短模式混用
    在這裡插入圖片描述

  • 也可以選項輸入多次
    在這裡插入圖片描述

  • opts接收可以解析的引數,當有剩餘引數時,就被另一個變數args接收
    在這裡插入圖片描述