[英]Run a function when importing module in Python
What I want to achieve: I have a function (object/module/etc) that allows me to run a model.我想要实现的目标:我有一个 function(对象/模块/等),它允许我运行 model。 This model requires a few parameters, so I want to have them in a config file rather than pass all through the code.
这个 model 需要一些参数,所以我想将它们放在一个配置文件中,而不是通过所有代码。 So what I want is to have a config file created automatically when my module is imported.
所以我想要的是在导入我的模块时自动创建一个配置文件。 Is it possible in python?
python 有可能吗? Can I have some pointers on where to start please?
请问我可以从哪里开始吗?
All the code in a python file is run when its imported. python 文件中的所有代码在导入时都会运行。 If you have
如果你有
def f():
print("ran")
print("imported")
Then when you import it it will print imported
This is also why you sometimes see if __name__=="__main__":
In some files.然后当你导入它时,它会打印
imported
这也是为什么你有时会看到if __name__=="__main__":
In some files。 The code in that block is only run if the file is run as main not imported.仅当文件作为未导入的 main 运行时,该块中的代码才会运行。 However creating files in a predetermined location may be bad UX, so if you want other people to use your library id think of a better solution.
但是,在预定位置创建文件可能是不好的用户体验,因此如果您希望其他人使用您的库 id,请考虑一个更好的解决方案。
Generally you can just put code at top level of a module and it will run.通常,您只需将代码放在模块的顶层即可运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.