如何防止从python中导入的模块执行模块代码? [英] How to prevent modules code execution from imported module in python?

查看:18
本文介绍了如何防止从python中导入的模块执行模块代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有文件

testone.py

if __name__ == "__main__":
    from testtwo import Fu
class Foo:
    def bar(self):
        print 'barrr'

testtwo.py

class Fu:
    def baz(self):
        print 'baz'

Fu().baz() # function call within module

如何在不运行模块 testtwo.py 中调用的函数的情况下从文件 testtwo.py 中导入类 Fu?我尝试解决检查名称的问题.运行文件 testone.py 将导致 shell 打印出 baz.

How do you import class Fu from file testtwo.py without running the function called within module testtwo.py? I tried resolving the issue checking the name. As is running the file testone.py will result in the shell printing out baz.

推荐答案

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.

这篇关于如何防止从python中导入的模块执行模块代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆