__name__ == "__main_

发布时间:2019-03-06 17:16:22编辑:auto阅读(1707)

    问题:
    __name__ == "__main__" 的作用是什么?

    # 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 interpreter)读取了源文件,它会执行其中的所有代码。

    在执行代码之前,它会定义几个特殊变量。举例来说,如果 Python 编译器将那个模块(源文件)当作主程序来运行,那么它会将变量 __name__ 的值设为 "__main__"。如果这个源文件是从其他模块导入(import)的,变量 __name__ 会被设为模块名。

    在你的案例中,让我们假设这是作为主函数来执行。例如,在命令行上输入 python threading_example.py。当设置完特殊变量,它会执行如下几个步骤:

    1. 执行 import 语句,加载模块;
    2. 评估 def 区域,创造一个函数对象以及一个指向它的变量 myfunction
    3. 读取 if 语句,看到 __name__"__main__" 相等,然后执行其中的代码。

    这么做的原因在于,有时候你写了一个模块(.py文件),它既可以直接执行,又可以被引入到其他模块中执行。通过执行 main 检查,有两个好处:

    1. 当你想将该模块作为程序运行时才执行代码;
    2. 当某人只想导入模块并自行调用函数时,不会执行该代码。

    该问答来源:

    https://stackoverflow.com/questions/419163/what-does-if-name-main-do

关键字