[英]How to change the value of a variable in a function from a different file in Python?
I have two files, say file1 and file2. 我有两个文件,例如file1和file2。 I want to be able to edit the value of a variable (epoch) from file1 in file2, but it is in the main() function in file1.
我希望能够从file2中的file1中编辑变量(纪元)的值,但是它在file1中的main()函数中。
File1.py File1.py
def main():
global epoch
epoch=1
train(args, model, device, train_loader, optimizer, epoch)
File2.py File2.py
global epoch
var = imageClassifier.main()
epochMenu = Menu(middleFrame)
subEpochMenu = Menu(epochMenu)
epochMenu.add_cascade(label="epoch", menu=subEpochMenu)
subEpochMenu.add_command(Label="1", command=imageClassifier.main(epoch ==
1))
subEpochMenu.add_command(Label="5", command=var.epoch == 5)
Please ignore my menu settings, I have been trying to get this bit working firt as it is more important. 请忽略我的菜单设置,我一直在尝试使此功能正常运行,因为它更重要。
From Python's FAQ : 来自Python的常见问题解答 :
How do I share global variables across modules?
如何在模块之间共享全局变量?
The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).
在单个程序中的各个模块之间共享信息的规范方法是创建一个特殊的模块(通常称为config或cfg)。 Just import the config module in all modules of your application;
只需将config模块导入应用程序的所有模块中即可; the module then becomes available as a global name.
然后该模块就可以作为全局名称使用。 Because there is only one instance of each module, any changes made to the module object get reflected everywhere.
因为每个模块只有一个实例,所以对模块对象所做的任何更改都会在所有地方反映出来。 For example:
例如:
config.py:
config.py:
x = 0 # Default value of the 'x' configuration setting
mod.py:
mod.py:
import config config.x = 1
main.py:
main.py:
import config import mod print(config.x)
In your case, this means you need to: 就您而言,这意味着您需要:
Create a file config.py
: 创建一个文件
config.py
:
epoch = 1
Modify file1.py
: 修改
file1.py
:
import config def main(): train(args, model, device, train_loader, optimizer, config.epoch)
Modify file2.py
: 修改
file2.py
:
import config ... subEpochMenu.add_command(Label="1", command=imageClassifier.main(config.epoch == 1))
One way, is by reading it from an outsource file. 一种方法是从外包文件中读取它。
File1.py
can access the file and write into it. File1.py
可以访问文件并将其写入。
So, under File1.py
you will have the following: 因此,在
File1.py
下,您将具有以下内容:
import json
dct = {"epoch": 7}
with open('config.json', 'w') as cf:
json.dump(dct, cf)
And File2.py
can read from that .json . 而
File2.py
可以从以.json读取。
So, under File2.py
you will have the following: 因此,在
File2.py
下,您将具有以下内容:
with open('config.json', 'r') as cf:
config = json.load(cf)
epoch = config['epoch']
print(epoch)
# 7
I think this is the better way to do it as you decouple the modules and having a more maintainable and salable code. 我认为这是实现此目的的更好方法,因为您可以将模块分离,并拥有更可维护和可销售的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.