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

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

问题描述

鉴于我有文件

testone.py

testone.py

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

testtwo.py

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天全站免登陆