简体   繁体   English

在 Python 中导入模块时运行 function

[英]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.

相关问题 在python中导入模块的功能 - Importing function of a module in python 在 another.py 中导入模块时,返回 function 和直接运行不一样? - When importing a module in another .py , return of function is different to directly run it? pytest:从pytest运行时模块不会导入,但可以在普通python上运行 - pytest : module is not importing when run from pytest but works on plain python 执行导入的 function 本身时,嵌套 python 模块导入的问题 - issue with nested python module importing when executing imported function itself 使用Python在其他模块中导入函数的返回值时出错 - Error when importing the returned value of a function in a different module using Python 从python模块导入时,它是要导入的类还是函数? - When importing from a python module is it a class that gets imported or a function? Python Azure Function 导入类/模块时运行不正确 - Python Azure Function not correctly running when importing a class/module 从模块python 3导入函数 - importing function from module python 3 返回时在函数中导入模块 - Importing module in a function when returning 导入模块,但解释器无法识别该模块python中的功能 - Importing a module but the interpreter is not recognizing the function in that module python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM