yc09od / python

0 stars 0 forks source link

Learn getopt for argv #2

Open yc09od opened 7 years ago

yc09od commented 7 years ago

https://my.oschina.net/u/1178546/blog/146996

yc09od commented 7 years ago

import sys print sys.arg sys.arg save all arg value as list sys.arg[1:] = arg from index 1 to the end. the first element is filename.py

yc09od commented 7 years ago

One example Code : try: opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "output="]) except getopt.GetoptError:

print help information and exit:

----------------------------

-h -o file --help --output=out file1 file2 opt = [('-h', ''), ('-o', 'file'), ('--help', ''), ('--output', 'out')] arg = ['file1','file2']

yc09od commented 7 years ago
  1. 使用短格式分析串"ho:"。当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":"号。所以"ho:"就表示"h"是一个开关选项;"o:"则表示后面应该带一个参数。
  2. 使用长格式分析串列表:["help", "output="]。长格式串也可以有开关状态,即后面不跟"="号。如果跟一个等号则表示后面还应有一个参数。这个长格式表示"help"是一个开关选项;"output="则表示后面应该带一个参数。
yc09od commented 7 years ago

元祖的使用 one,two = (1,2) one = 1, two = 2