python获取命令行输入的参数

from optparse import OptionParser
optParser = OptionParser()
optParser.add_option('-f', '--file', action='store', type='string', dest='filename')
optParser.add_option('-v', '--version', action='store_false', dest='verbose', default='hello', help='make lots of noise [default]')
# optParser.parse_args() 剖析并返回一个字典和一个列表
# 字典中的关键字是我们在每一个add_option中添加的dest参数值
# 而对应的value值,是add_option中的default参数或者是由用户传入optparse.parse_args()的参数
fakeArgs = ['-f','file.txt', '-v', 'how are u', 'arg1', 'arg2']
option, args = optParser.parse_args()
op, ar = optParser.parse_args(fakeArgs)
print(f'options : {option}', f'args : {args}', f'op : {op}', f'ar : {ar}', sep='\n')
# 注意两种调用方式的区别,第二种方式是模拟命令行输入
# 当action设置为store时,命令行传入的参数会保存字option对象中,
# 当设置为store_false时不会保存,传入参数则对应的value为None,否则为默认值, store_true正好相反