python运行时修改另一个py文件的数据的程序并保存
时间: 2023-04-03 09:04:37 浏览: 465
你可以使用 Python 的内置模块 `importlib` 来动态加载模块,然后使用 `setattr` 函数来修改模块中的变量值,最后使用 `pickle` 模块将修改后的数据保存到文件中。以下是一个示例代码:
```python
import importlib
import pickle
# 加载要修改的模块
module_name = 'module_to_modify'
module = importlib.import_module(module_name)
# 修改模块中的变量值
module.variable_to_modify = new_value
# 将修改后的数据保存到文件中
with open('modified_data.pkl', 'wb') as f:
pickle.dump(module.variable_to_modify, f)
```
其中,`module_to_modify` 是要修改的模块名,`variable_to_modify` 是要修改的变量名,`new_value` 是新的变量值,`modified_data.pkl` 是保存修改后数据的文件名。
相关问题
如何在Ubuntu系统中将Windows主机上的Python脚本文件(.py)映射到Docker容器的demodirectory目录中?使得只需要修改windows中的python文件,而运行容器中的demo文件中时能运行修改的程序。
在Ubuntu系统中,你可以通过以下步骤将Windows主机上的Python脚本映射到Docker容器的`demodirectory`目录:
1. **创建并启动Docker容器**:
使用以下命令创建一个基于适合你的Python应用的镜像,并指定`demodirectory`作为数据卷:
```
docker run -d --name my_container -v /path/to/your/windows/python/script:/demodirectory your_python_image
```
将`/path/to/your/windows/python/script`替换为你实际的Windows Python脚本文件路径。
2. **挂载共享目录**:
确保在启动时已经指定了数据卷共享,这会保证你在Windows上对脚本所做的任何改动都会实时反映到容器内的`demodirectory`。
3. **在容器内运行脚本**:
在容器内部,你可以在`demodirectory`下直接运行脚本,例如:
```bash
python demodirectory/your_script.py
```
4. **更新脚本**:
在Windows上编辑脚本文件,保存后无需重启容器,因为它们在数据卷中是同步的。
注意,为了使这个设置正常工作,你需要确保主机和容器的操作系统之间文件系统的兼容性,通常Windows和Linux之间的文件权限可能会有所不同,需要适当处理。
pyqt5修改其他py文件的变量数据,停止运行后不改变的程序
我可以回答这个问题。在 Python 中,如果你想要修改其他 py 文件中的变量数据,可以使用 importlib.reload() 函数重新加载该文件,然后再修改变量数据。但是,如果程序停止运行后,变量数据没有改变,可能是因为你没有将修改后的数据保存到文件中。你可以使用 pickle 模块将数据保存到文件中,以便下次运行程序时可以读取到修改后的数据。
阅读全文
相关推荐















