1. 程式人生 > >python中if __name__ == '__main__':

python中if __name__ == '__main__':

not pri ons import lee ng- iter eas port

Using a module‘s __name__

Example? 8.2.? Using a module‘s __name__

				
#!/usr/bin/python
# Filename: using_name.py

if __name__ == ‘__main__‘:
	print ‘This program is being run by itself‘
else:
	print ‘I am being imported from another module‘
				
				

Output

				
$ python using_name.py
This program is being run by itself

$ python
>>> import using_name
I am being imported from another module
>>>
				
				

How It Works

Every Python module has it‘s __name__ defined and if this is ‘__main__‘, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

# Threading example
import time, thread

def myfunction(string, sleeptime, lock, *args):
    while 1:
        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))

還有*args在這裏是什麽意思?


當Python解析器讀取一個源文件時,它會執行所有的代碼.在執行代碼前,會定義一些特殊的變量.例如,如果解析器運行的模塊(源文件)作為主程序,它將會把__name__變量設置成"__main__".如果只是引入其他的模塊,__name__變量將會設置成模塊的名字.

假設下面是你的腳本,讓我們作為主程序來執行:

python threading_example.py

當設置完特殊變量,它就會執行import語句並且加載這些模塊.當遇到def代碼段的時候,它就會創建一個函數對象並創建一個名叫myfunction變量指向函數對象.接下來會讀取if語句並檢查__name__

是不是等於"__main__",如果是的話他就會執行這個代碼段.

這麽做的原因是有時你需要你寫的模塊既可以直接的執行,還可以被當做模塊導入到其他模塊中去.通過檢查是不是主函數,可以讓你的代碼只在它作為主程序運行時執行,而當其他人調用你的模塊中的函數的時候不必執行.

python中if __name__ == '__main__':