更新时间:2023-11-08 16:30:16
python 如何防止模块代码从模块执行?
How to prevent modules code execution from module in python?
你不能,当你导入一个模块时,它会运行在全局范围内调用的所有东西.
You can't, when you import a module, it runs everything that is called in the global scope.
您可以更改它以便轻松调用或不调用:
You can change it so that it's easy to call or not:
def main():
Fu().baz()
if __name__ == '__main__':
main()
然后当你想要调用它时,你导入它并调用 main()
并且当你将它作为主模块运行时它仍然会自动运行.
And then when you want it called you import it and call main()
and it will still automatically run when you run it as the main module.