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

2024-05-15 07:47:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想解码python脚本参数,存储并分析它们。在以下命令中,-r选项用于确定要创建的报告类型

python脚本启动: %run decodage_parametres_script.py -r junit,html

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

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

然后我想测试-r选项,下面是代码:

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")    

我想尝试默认报告生成,但我甚至没有点击打印(“请求xml导出”)行,以下是控制台结果:

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':应该以True结尾,但事实并非如此。 我是不是错过了一些琐碎的事情

有人能帮我吗


Tags: pathin脚本forhtml选项tracereporter
1条回答
网友
1楼 · 发布于 2024-05-15 07:47:08

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

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']))

解决方案2
更改比较器:

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

if i == 'junit':

相关问题 更多 >