Python获取命令行参数后进行处理的时候为什么不能进到else中,请大神赐教哈
迷茫
迷茫 2017-04-18 09:44:25
0
2
726
# 获取命令行参数
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)
        
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
洪涛

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循环中去的, 自然也不会触发elsewhen you run the script without parameters.

Let’s do a test:

lst = []
for i in lst:
    if i:
        print(i)
    else:
        print("hello")
# 结果为空, for循环并没有执行
lst = [0]
for i in lst:
    if i:
        print(i)
    else:
        print("hello")
# 列表非空, 可迭代, 正常进入else

So your code should be rewritten as:

# coding=utf8
import getopt
import sys


def usage():
    print("{}: '-i p_case_dir -n p_case_id_str -o p_out_dir -s p_src_conn -d p_dst_conn'".format(sys.argv[0]))


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:n:o:s:d:")
    except getopt.GetoptError as e:
        print(e)
        usage()
        sys.exit(1)
    if opts:
        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
            else:
                usage()
                sys.exit(1)
    else:
        usage()
        sys.exit(1)

if __name__ == "__main__":
    main()

In addition, starting from Python 2.7, it is more flexible and convenientargparse被纳入标准库, 所以建议用来代替getopt
Official website manual

迷茫

Because the following sentence has already reported an exception:

opts,args = getopt.getopt(sys.argv[1:],"hi:n:o:s:d:")

Exceptions need to be caught in advance:

try:
    opts,args = getopt.getopt(sys.argv[1:],"hi:n:o:s:d:")
except getopt.GetoptError:
    print('This options is not supported.')
    exit(-1)

Then handle the input of normal parameters in your if/elif/else.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template