In python modules can be loaded by importing in some other module or executed directly as standalone program. So, how does python detect at run time that a particular module was imported or it was executed directly as standalone application.
Simple answer is : using system defined variable __name__.
When a module is imported __name__ variable contains module name.However, __name__ contains __main__ if executed directly.
Illustration:-
Create a file name "parentmodule.py" with following code lines.
Create another file "test.py" with following code lines
Sample output:-
C:\Python27\pgm>python parentmodule.py
I have run as application.
C:\Python27\pgm>python test.py
I have been imported.
Simple answer is : using system defined variable __name__.
When a module is imported __name__ variable contains module name.However, __name__ contains __main__ if executed directly.
Illustration:-
Create a file name "parentmodule.py" with following code lines.
def importedmodule(): print "I have been imported." def directexecution(): print "I have run as application." #Executed directly as application if __name__ == '__main__': directexecution() else: importedmodule()
Create another file "test.py" with following code lines
import parentmodule def importedmodule(): print "I have been imported." def directexecution(): print "I have run as application."Now run parentmodule.py directly, it will call method directexecution(). However, if we run test.py - importedmodule() method is executed, because parentmodule has been imported in test.py so __name__ is not equal to __main__.
Sample output:-
C:\Python27\pgm>python parentmodule.py
I have run as application.
C:\Python27\pgm>python test.py
I have been imported.
Tags:
Python
Mua vé tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ tháng nào rẻ nhất
lịch bay từ california về việt nam
vé máy bay từ vinh đi sài gòn
vé máy bay huế - hà nội
săn vé giá rẻ đi nha trang
taxi đi sân bay nội bài
combo du lịch đà lạt nha trang