# 获取命令行参数
opts,args = getopt.getopt(sys.argv[1:],"hi:n:o:s:d:")
#function to show help information when user input "-h"
def usage():
print ("sys.argv[0]: ' -i p_case_dir -n p_case_id_str -o p_out_dir -s p_src_conn -d p_dst_conn'")
print ("sys.argv[0]: ' -h'")
for op,value in opts:
if(op == "-i"):
p_case_dir = value
elif(op == "-n"):
p_case_id_str = value
elif(op == "-o"):
p_out_dir = value
elif(op == "-s"):
p_src_conn = value
elif(op == "-d"):
p_dst_conn = value
elif(op == "-h"):
usage()
os._exit(0)
else:
usage()
os._exit(0)
The real reason is the logic of
opts, args = getopt.getopt(sys.argv[1:], "hi:n:o:s:d:")
这句得到的opts = []
, 即一个空的list
且并不像楼上说的会报异常错误, 而对于一个空的list
来说, 你这句for op,value in opts:
是不会进入到for
循环中去的, 自然也不会触发else
when you run the script without parameters.Let’s do a test:
So your code should be rewritten as:
In addition, starting from Python 2.7, it is more flexible and convenient
argparse
被纳入标准库, 所以建议用来代替getopt
Official website manual
Because the following sentence has already reported an exception:
Exceptions need to be caught in advance:
Then handle the input of normal parameters in your if/elif/else.