본문 바로가기
<개인공부> - IT/[Python]

What does if __name__ == “__main__”: do?

by Aggies '19 2018. 9. 15.
반응형

궁금해서 찾아보았는데 과제하는데 도움이 될 것 같아서 공부삼아 기록한다.


When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.


결국은 실행할 main 함수가 없으면 indentation level 0에 해당하는 것이 implicit하고 main으로 간주하고 실행한다는 말.


# file one.py
def func():
print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")


# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
print("two.py is being run directly")
else:
print("two.py is being imported into another module")



python one.py # When one.py executes

top-level in one.py
one.py is being run directly



python two.py # When two.py executes

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly


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

반응형