python的新手,试图了解为什么会发生这种情况

时间:2018-08-09 14:13:39

标签: python

给出:

import argparse
parser.add_argument("-t", "--test", type=str.lower, nargs='+')
args = parser.parse_args()

if 'test1' in args.test:
    my_test = 'Test1'
    print("Testing", my_test)
if 'test2' in args.test:
    my_test = 'Test2'
    print("Testing", my_test)
else:
    print("Invalid test defined:", args.test)

“ my_test.py -t test1”为什么会导致:

Testing Test1
Invalid test defined: ['test1']

有效结果,但有错误

但是“ my_test.py -t test1 test2”可以按预期工作:

Testing Test1
Testing Test2

2 个答案:

答案 0 :(得分:1)

这正是程序应该执行的操作。您的其他条款是针对Test2案例的。 Test1案例没有else子句。您的代码检查test1和test2,但是当test2不存在时,它将进入else子句。 由于我不知道您的要求,因此可以使用else if test2子句轻松解决此问题。

答案 1 :(得分:0)

谢谢!您向我指出了正确的方向,但是如果-elif无法正常工作,因为它只会运行第一个比赛。我的解决方案:

    TESTS = ['test1','test2']

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--test", type=str.lower, nargs='+')
    args = parser.parse_args()

    if args.test:
      for my_test in sorted(args.test):
        if my_test in sorted(TESTS):
          print("Testing", my_test)
        else:
          print("Invalid test defined:", my_test)

给予:

    python3 ./test -t test2
        Testing test2

    python3 ./test -t test2 test1
        Testing test2
        Testing test1

    python3 ./test -t test2 test1 notest
        Invalid test defined: notest
        Testing test1
        Testing test2
相关问题