What is if __name__ == '__main__':?

김정현·2023년 3월 9일
0

code

목록 보기
1/1

Refrence url

If you look at the Python code on the Internet, you will see a part that starts with the following code.

if __name__ == '__main__':
	blah

Why are you using this code ?

This code is used to get the status of the current running script file.

Let's start with __name__. Save the following as a hello.py file in your project folder (C:\project).

# hello.py
print('hello 모듈 시작')
print('hello.py __name__:', __name__)    # __name__ 변수 출력
print('hello 모듈 끝')

Then, save the following content as a main.py file in the project folder (C:\project) and run it.

# main.py
import hello    # hello 모듈을 가져옴
 
print('main.py __name__:', __name__)    # __name__ 변수 출력
# Result
hello 모듈 시작
hello.py __name__: hello
hello 모듈 끝
main.py __name__: __main__

When running, it will output the value of the __name__ variable in the hello.py and main.py files.

When you import a module with an import in Python, its script file is executed once. So, importing the hello module will execute the code inside hello.py. So put 'hello' in the __name__ variable of hello.py and __main__ in the __name__ variable of main.py.

Python makes no difference between a script file and a module that you start with. Any script file can be a starting point or a module. So the __name__ variable determines whether the current script file is a starting point or a module.

The code that checks whether the value of the __name__ variable is __main__, such as if __name__=='__main__': determines whether the current script file is the starting point of the program. That is, it is used to distinguish when a script file is used as a main program and when used as a module.

profile
대학원 생활

0개의 댓글