python - 多次运行相同的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]。我希望我说清楚了
解决方案
你从操作系统命令行调用它两次 - 比如说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)
您可以根据需要创建任意数量的实例,所有实例都相互独立,并且都保持自己的状态。
推荐阅读
- php - the_content() AND apply_filters('the_content'... ) 在页面的第二个循环中不起作用
- python - 您如何在 Robot Framework 中编写具有多个标识符的动态元素?
- python - SSH到远程机器并使用python在多个主机IP上运行后台ping
- c++ - 将代码提交到 coursera 时出现“未知信号 11”问题。如果我使用二维向量而不是二维数组,问题就会得到解决
- javascript - react-select如何在点击使用打字稿时显示选项
- java - 跨子类的标准化构造函数?
- php - 试图获取非对象的属性“id” - Laravel
- excel - 根据输入范围在 VBA 中输出图形
- bash - 在bash中设置vim路径
- javascript - 从子组件传递时在父组件中保存状态 - 用于多个项目(React Hooks)