getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数。命令行选项使程序参数更加灵活,支持短格式命令模式(-)和长格式命令模式(--)。
import getopt
import sys
def help_msg():
print('*' * 40)
print('-h or --help= 指定server的ip地址')
print('-p or --port= 指定server的连接port')
print('*' * 40)
def main():
options, args = getopt.getopt(sys.argv[1:], 'h:p:', ['port=', 'host=', 'help'])
print(options)
print(args)
for name, value in options:
if name in ('--help',):
help_msg()
if name in ('-h', '--host'):
print("value: {0}".format(value))
if name in ('-p', '--port'):
print("value: {0}".format(value))
if __name__ == '__main__':
main()
执行命令,查看帮助信息
python .\demo02.py --help
输出信息如下
[('--help', '')]
[]
****************************************
-h or --help= 指定server的ip地址
-p or --port= 指定server的连接port
****************************************
执行命令,传递参数
python .\demo02.py -h 192.168.1.222 -p 443
或者
python .\demo02.py --host=192.168.1.222 --port=443
结果如下:
[('-h', '192.168.1.202'), ('-p', '443')]
[]
value: 192.168.1.202
value: 443
这里可以看到args参数一直为空,args是个列表,其中的元素是那些不含'-'或'--'的参数
python .\demo02.py -h 192.168.1.202 -p 443 args1 args2 args2
输出结果
[('-h', '192.168.1.202'), ('-p', '443')]
['args1', 'args2', 'args2']
value: 192.168.1.202
value: 443
参考:
import sys
import getopt
def main(argv):
input_file = ""
output_file = ""
# "hi:o:": 短格式分析串, h 后面没有冒号, 表示后面不带参数; i 和 o 后面带有冒号, 表示后面带参数
# ["help", "input_file=", "output_file="]: 长格式分析串列表, help后面没有等号, 表示后面不带参数; input_file和output_file后面带冒号, 表示后面带参数
# 返回值包括 `opts` 和 `args`, opts 是以元组为元素的列表, 每个元组的形式为: (选项, 附加参数),如: ('-i', 'test.png');
# args是个列表,其中的元素是那些不含'-'或'--'的参数
opts, args = getopt.getopt(argv[1:], "hi:o:", ["help", "input_file=", "output_file="])
for opt, arg in opts:
if opt in ("-h", "--help"):
print('script_2.py -i <input_file> -o <output_file>')
print('or: test_arg.py --input_file=<input_file> --output_file=<output_file>')
sys.exit()
elif opt in ("-i", "--input_file"):
input_file = arg
elif opt in ("-o", "--output_file"):
output_file = arg
print('输入文件为:', input_file)
print('输出文件为:', output_file)
# 打印不含'-'或'--'的参数
for i in range(0, len(args)):
print('不含'-'或'--'的参数 %s 为:%s' % (i + 1, args[i]))
if __name__ == "__main__":
main(sys.argv)