代码之家  ›  专栏  ›  技术社区  ›  A.Joly

虽然类型比较在终端中有效,但断言在脚本中无效

  •  0
  • A.Joly  · 技术社区  · 7 年前

    我遇到了一个比较奇怪的问题。

    %run decodage_parametres_script.py -r junit,html

    python脚本选项解析用于填充字典,结果是:

    {'-cli-no-summary': False, '-cli-silent': False, '-r': ['junit', 'html']}

    for i in current_options['-r']:
        # for each reporter required with the -r option:
        #    - check that a file path has been configured (otherwise set default)
        #    - create the file and initialize fields
        print("trace i", i)
        print("trace current_options['-r'] = ", current_options['-r'])
        print("trace current_options['-r'][0] = ", current_options['-r'][0])
    
        if current_options['-r'][i] == 'junit':
            # request for a xml report file
            print("request xml export")
            try:
                xml_file_path = current_option['--reporter-junit-export']
                print("xml file path = ", xml_file_path)
            except:
                # missing file configuration
                print("xml option - missing file path information")
                timestamp = get_timestamp()
                xml_file_path = 'default_report' + '_' + timestamp + '.xml'
                print("xml file path = ", xml_file_path)
            if xml_file_path is not None:
                touch(xml_file_path)
                print("xml file path = ", xml_file_path)
            else:
                print('ERROR: Empty --reporter-junit-export path')
                sys.exit(0)
        else:
            print("no xml file required")    
    

    trace i junit
    trace current_options['-r'] =  ['junit', 'html']
    trace current_options['-r'][0] =  junit
    

    In [557]: for i in current_options['-r']:
     ...:     print(i, type(i))
     ...:
    junit <class 'str'>
    html <class 'str'>
    
    In [558]: toto = 'junit'
    
    In [559]: type(toto)
    Out[559]: str
    
    In [560]: toto
    Out[560]: 'junit'
    
    In [561]: toto == current_options['-r'][0]
    Out[561]: True
    

    所以我的主张 if current_options['-r'][i] == 'junit' 我是否错过了一些琐碎的事情(

    有人能帮我吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Laser    7 年前

    您正在按字符串数组进行迭代

    for i in current_options['-r']:
    

    i 将:
    junit 第一次迭代时
    html

    您的if条件(从解释器的角度来看)将如下所示:

      if current_options['-r']['junit'] == 'junit':
    

      if current_options['-r'][0] == 'junit':
    

    解决方案1:
    您需要迭代 range(len(current_options['-r']))


    更改比较器:
    从…起

    if current_options['-r'][i] == 'junit':
    

    if i == 'junit':