python中的 if __name__ == “__main__”: 有什么用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python中的 if __name__ == “__main__”: 有什么用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2611字,纯文字阅读大概需要4分钟。
内容图文
![python中的 if __name__ == “__main__”: 有什么用](/upload/InfoBanner/zyjiaocheng/852/1ab6b05e6e294d8492553829e8743413.jpg)
https://stackoverflow.com/questions/419163/what-does-if-name-main-do#
问题:
What does if name == “main”: do?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while True:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
解答:
当 Python 解释器读取源文件时, 它将执行在其中找到的所有代码。
在执行代码之前, 它将定义一些特殊的变量。例如, 如果 Python 解释器正在将该模块 (源文件) 作为主程序运行, 则会将特殊的 "name" 变量设置为具有值 "main "。如果从另一个模块导入此文件, "name" 将被设置为模块的名称。
在您的脚本的情况下, 让我们假设它的执行作为主要功能, 例如, 你说的东西像
python threading_example
在命令行上。设置特殊变量后, 它将执行导入语句并加载这些模块。然后, 它将评估 def 块, 创建一个函数对象, 并创建一个名为 myfunction 的变量, 指向函数对象。然后, 它将读取 if 语句, 并看到 name 执行相等 "main ", 因此它将运行显示在那里的块。
这样做的一个原因是, 有时您编写的模块 (. py 文件) 可以直接执行。或者, 它也可以导入并在另一个模块中使用。通过执行main检查, 只有当您希望将模块作为程序运行时才执行该代码. 而当有人只想导入您的模块并调用您的函数时, 不执行main函数。
原文:
When the Python interpreter reads a source file, it executes all of the code found in it.
Before executing the code, it will define a few special variables. For example, if the Python interpreter is running that module (the source file) as the main program, it sets the special __name__
variable to have a value "main". If this file is being imported from another module, __name__
will be set to the module's name.
In the case of your script, let's assume that it's executing as the main function, e.g. you said something like
python threading_example.py
on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that name does equal "main", so it will execute the block shown there.
One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
内容总结
以上是互联网集市为您收集整理的python中的 if __name__ == “__main__”: 有什么用全部内容,希望文章能够帮你解决python中的 if __name__ == “__main__”: 有什么用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。