You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何在其他函数中使用main函数内更新后的字典

Python 变量共享问题解决方案

以下是3种可直接落地的实现方案,按推荐优先级排序:

方案1:将更新后的字典作为参数传递(最推荐)

该方案符合Python无副作用函数设计规范,无全局变量污染,逻辑清晰易维护。

修改步骤:

  1. 调整read_file函数签名,增加参数接收外部传入的更新后字典
  2. 在main函数完成newDict的更新逻辑后,调用read_file时传入参数

修改后代码示例

# 修改read_file定义,增加入参
def read_file(rev_dict, updated_newDict):
    shutil.copy("logfile.log", "file.txt")
    # 推荐使用with语句自动管理文件关闭,避免资源泄漏
    with open("file.txt", "r+", encoding="utf-8") as f:
        # 可根据实际需求调整表头,比如展示测试用例和执行结果
        headers = ['Testcase', '执行结果']
        data = sorted([(k, v) for k, v in updated_newDict.items()])
        f.write(tabulate(data, headers=headers, tablefmt="grid"))
    sys.exit(0)

def main():
    rev_dict, newDict = file_reader()
    parser = ap.ArgumentParser()
    parser.add_argument('-s', '--start', help='start script', action='store_true')
    args = parser.parse_args()

    if args.start: # 注意原代码这里缺少if直接写elif,会报语法错误
        for k,v in rev_dict.items():
            print("\nTestcase:" + v + "\n")
            print(v, "=", k)
            print("\n")
            time.sleep(5)
            proc = sp.call([k], shell=True)
            time.sleep(5)
            print('Process ID is:', os.getpid())
            if proc != 0:
                if proc < 0:
                    print("\nKilled by signal!\n", -proc)
                else:
                    print("\nFailed with return code: ", proc)
                    newDict[v] = 'Fail'
                    # 原代码这里dic未定义,替换为newDict
                    print(json.dumps(newDict, indent=4, sort_keys=True))
            else:
                print("\nOK\n")
                newDict[v] = 'Pass'
                print(json.dumps(newDict, indent=4, sort_keys=True))
                sipResponse(args.ip)
        # 所有测试用例执行完成、newDict更新完毕后,调用报表生成函数传入参数
        read_file(rev_dict, newDict)

方案2:使用全局变量存储更新后的字典

该方案实现简单,但仅适合小型脚本使用,大型项目会引入变量污染、状态不可控等问题,不推荐长期使用。

代码示例

# 在全局作用域定义共享变量
global_rev_dict = {}
global_new_dict = {}

def main():
    global global_rev_dict, global_new_dict
    rev_dict, newDict = file_reader()
    global_rev_dict = rev_dict
    # ... 原有业务逻辑,更新newDict ...
    global_new_dict = newDict
    # 调用报表函数无需传参
    read_file()

def read_file():
    global global_rev_dict, global_new_dict
    # 直接使用全局作用域的更新后字典即可
    shutil.copy("logfile.log", "file.txt")
    with open("file.txt", "r+", encoding="utf-8") as f:
        headers = ['Testcase', '执行结果']
        data = sorted([(k,v) for k,v in global_new_dict.items()])
        f.write(tabulate(data, headers=headers, tablefmt="grid"))
    sys.exit(0)

方案3:封装为类管理状态(适合中大型项目)

如果后续业务逻辑需要扩展,将配置读取、测试执行、报表生成的相关逻辑和状态封装到类中,通过实例属性共享数据,可维护性更高。

代码示例

import configparser
import argparse as ap
import subprocess as sp
import time
import os
import json
import shutil
from tabulate import tabulate
import sys

class TestExecutor:
    def __init__(self):
        self.rev_dict, self.new_dict = self._file_reader()
        self.args = self._parse_args()
    
    def _file_reader(self):
        # 原有file_reader逻辑
        config_dict = {}
        newDict = {}
        configParser = configparser.ConfigParser()
        configParser.read('config.ini')
        for section in configParser.sections():
            for k,v in configParser.items(section):
                config_dict[k] = v
        config_dict = dict(configParser.items('SectionTwo'))
        rev_dict = dict(map(reversed, configParser.items('SectionOne')))
        for v in rev_dict:
            newDict[k] = rev_dict[v]
        return rev_dict, newDict
    
    def _parse_args(self):
        parser = ap.ArgumentParser()
        parser.add_argument('-s', '--start', help='start script', action='store_true')
        return parser.parse_args()
    
    def run_test(self):
        if self.args.start:
            for k,v in self.rev_dict.items():
                print(f"\nTestcase:{v}\n")
                print(f"{v} = {k}")
                time.sleep(5)
                proc = sp.call([k], shell=True)
                time.sleep(5)
                print(f"Process ID is: {os.getpid()}")
                if proc != 0:
                    if proc < 0:
                        print(f"\nKilled by signal!\n{-proc}")
                    else:
                        print(f"\nFailed with return code: {proc}")
                        self.new_dict[v] = 'Fail'
                else:
                    print("\nOK\n")
                    self.new_dict[v] = 'Pass'
                print(json.dumps(self.new_dict, indent=4, sort_keys=True))
    
    def generate_report(self):
        shutil.copy("logfile.log", "file.txt")
        with open("file.txt", "r+", encoding="utf-8") as f:
            headers = ['Testcase', '执行结果']
            data = sorted([(k,v) for k,v in self.new_dict.items()])
            f.write(tabulate(data, headers=headers, tablefmt="grid"))
        sys.exit(0)

if __name__ == "__main__":
    executor = TestExecutor()
    executor.run_test()
    executor.generate_report()

内容的提问来源于stack exchange,提问作者Asad Javed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:09:01