首页 > 解决方案 > 多次运行相同的python脚本会混合变量

问题描述

我想将一些数据传递给另一个 python 脚本并在那里做一些事情。但是,如果我使用不同的参数同时多次运行脚本,我发送的数据就会发生冲突。我如何将它们分开?

示例代码:

主文件

import otherscript

list_a = [1,2,3] # from arguments
otherscript.append_to_another_list(list_a)

其他脚本.py

another_list = []
def append_to_another_list(list):
    another_list.append(list)
    print(another_list)

如果我使用参数 1,2,3 和 4,5,6 同时运行 main.py 两次,它会将它们都打印在同一个列表中,如 [1,2,3,4,5,6]。我希望我说清楚了

标签: python

解决方案


你从操作系统命令行调用它两次 - 比如说bash- 你会期望它们完全独立,而不是显示 OP 描述的行为。

另一方面,在单个 Python 解释器中,一个模块只初始化一次,因此otherscript模块中的列表(它是一个模块而不是脚本)将保留并继续附加。

无论如何,也许你最好的更好控制的选择是一个类。

class ListKeeper:
    def __init__(self):
        self.another_list = []

    def append_to_another_list(self, list):
        self.another_list.append(list)
        print(another_list)

main.py会看起来像:

import otherscript

list_a = [1,2,3] # from arguments
keeper1 = otherscript.ListKeeper()
keeper1.append_to_another_list(list_a)

您可以根据需要创建任意数量的实例,所有实例都相互独立,并且都保持自己的状态。


推荐阅读