全局名称空间中的argparse参数将覆盖其他文件的参数

如何解决全局名称空间中的argparse参数将覆盖其他文件的参数

这是我在自动脚本开发期间注意到的一种行为。 现在我有两个文件main.pytest.py
main.py代码

#!/usr/bin/env python3
import argparse
import os
import sys
import time
from pathlib import Path
import pytest
import configparser as cpaser

test_config = {}

def config_test_env():
    global test_config
    case_path = Path(base_dir,'testcase')
    Now = time.strftime("%Y-%m-%d_%H-%M-%s")
    test_reports_address = Path(base_dir,'report')
    test_log_address = Path(base_dir,'log')
    if not test_reports_address.exists():
        os.mkdir(test_reports_address)
    if not test_log_address.exists():
        os.mkdir(test_log_address)
    filepath = Path(test_reports_address,Now + "_report.html")
    test_config['filepath'] = str(filepath)
    parser = argparse.ArgumentParser(description='main.py - excute testcases')
    parser.add_argument('-H','-Host',dest='host',help='host url',default='http://192.168.1.169')
    parser.add_argument('-t',dest='testcase_path',help='testcase path',type=str,default=case_path)
    parser.add_argument('-r',dest='test_report_path',help='testreport path',default=filepath)
    parser.add_argument('-m',help='run specific mark type testcase',choices=['smoke_test','ui_test','api_test','demonstration'])
    parser.add_argument('--driver',help='specific webdriver to perform UI test',default='chrome')
    parser.add_argument('-s',help='print testcase execute result on screen',action='store_true')
    parser.add_argument('-c',help='enable code coverage check',action='store_true')
    parser.add_argument('-cr','-check_response_time',help='check API reponse time',dest='ct',action='store_true',default=False)
    parser.add_argument('-dc','-delete_case',dest='delete_case_flag',help='whether delete case after testcase finish',default=False)
    parser.add_argument('-mt','-max_response_time',dest='mt',help='api max response time set',default=30,type=int)
    parser.add_argument('-sr','-send_report',dest='send_report',help='whether send report after test excute',default=False)
    args = parser.parse_args()
    host = str(args.host)
    test_config['host'] = host
    ct_flag = args.ct
    csv_file_path = str(Path(base_dir,host.split('//')[1] + '_api_response_time.csv'))
    test_config['csv_file_path'] = csv_file_path
    test_config['ct_flag'] = ct_flag
    mt = args.mt
    test_config['mt'] = mt
    if ct_flag:
        create_csv_file(csv_file_path)
    dc_flag = args.delete_case_flag
    test_config['dc_flag'] = dc_flag
    test_config['send_report'] = args.send_report
    pytest_args = [
        '-v',str(args.testcase_path),'--html=' + str(args.test_report_path),'--self-contained-html','--driver',str(args.driver)
    ]
    test_config['pytest_args'] = pytest_args


config_test_env()

if __name__ == '__main__':
    # pytest main
    pass

test.py代码

from main import test_config

if __name__ == '__main__':
    # pytest main
    parser = argparse.ArgumentParser(description='store case using thread')
    parser.add_argument('-t','-total',dest='total_case',help='total_case number',type=int,default=100)
    parser.add_argument('-r',dest='per_round',help='case number per round,thread number',default=100)
    args = parser.parse_args()
    pass

我希望main.py设置一些全局变量,以便将方法config_test_env放在全局名称空间中并更新全局test_confg,以便可以由其他文件导入。
但是当我执行python3 test.py -h时,输出是:

usage: test2.py [-h] [-H HOST] [-t TESTCASE_PATH] [-r TEST_REPORT_PATH] [-m {smoke_test,ui_test,api_test,demonstration}] [--driver DRIVER] [-s] [-c] [-cr] [-dc] [-mt MT] [-sr]

main.py - excute testcases

optional arguments:
  -h,--help            show this help message and exit
  -H HOST,-Host HOST   host url
  -t TESTCASE_PATH      testcase path
  -r TEST_REPORT_PATH   testreport path
  -m {smoke_test,demonstration}
                        run specific mark type testcase
  --driver DRIVER       specific webdriver to perform UI test
  -s                    print testcase execute result on screen
  -c                    enable code coverage check
  -cr,-check_response_time
                        check API reponse time
  -dc,-delete_case     whether delete case after testcase finish
  -mt MT,-max_response_time MT
                        api max response time set
  -sr,-send_report     whether send report after test excute

显然test.py参数似乎被main.py所取代,所以我想知道可以从main.py导入全局变量但又不覆盖参数的解决方

解决方法

执行from main import test_config时,整个main模块将被执行。

由于对config_test_env()的调用不受if __name__ == '__main__':的保护,因此在导入过程中被调用。

在此调用中,您定义一个parser,然后调用args = parser.parse_args()。因为您是使用-h来运行的,所以对parse_args的调用将显示{main的帮助消息,并退出程序。


关于解决此问题,很难说,因为我不完全了解您在做什么。将config_test_env()放在if __name__ == '__main__':下,或者至少仅parser创建应仅在文件为主文件时执行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?