模块可以通过查看预定义的全局变量 __name__ 来找到自己的模块名称。如果其值为“__main__”,则程序作为脚本运行。
def main(): print('Testing…...') ... if __name__ == '__main__': main()
Testing…...
通常通过导入使用的模块也提供命令行界面或自测试,并且仅在检查 __name__ 后才执行此代码。
__name__是Python语言中的一个内置变量,我们可以编写一个程序来查看这个变量的值。这是一个例子。我们还将检查类型 -
print(__name__) print(type(__name__))
__main__ <type 'str'>
Let’s see another example -
立即学习“Python免费学习笔记(深入)”;
我们有一个文件 Demo.py。
def myFunc(): print('Value of __name__ = ' + __name__) if __name__ == '__main__': myFunc()
Value of __name__ = __main__
Now, we will create a new file Demo2.py. In this we have imported Demo and called the function from Demo.py.
import Demo as dm print('Running the imported script') dm.myFunc() print('\n') print('Running the current script') print('Value of __name__ = ' + __name__)
Running the imported script Value of __name__ = Demo Running the current script Value of __name__ = __main__
以上就是如何在Python中找到当前模块名称?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号