본문 바로가기
프로그래밍/Python 관련 정보

[Python Programming 기초] __main__

by 물박사의 저장공간 2024. 11. 11.

Github코드를 보다보면 가끔 발견하는 __main__의 정체에 대해 간단히 알아볼까요?

이 녀석은 import module의 코드를 실행하고 싶지 않을 때 사용하는 녀석입니다. 기본적으로 import 된 모듈은 "__name__"에 자신의 모듈명이 저장되어 있고, 현재 코드를 실행하는 모듈은 "__name__"에 "__main__"가 저장되어 있으므로 모듈을 직접 실행시키는 경우에만 모듈 내 테스트 코드가 실행되도록 하기 위한 코드입니다. 

 

예를 들어

# example_module.py

def greet():
    print("Hello! This function is in example_module.")

# 테스트 코드 또는 직접 실행하고 싶은 코드
if __name__ == "__main__":
    print("example_module is being run directly.")
    greet()
else:
    print("example_module has been imported.")

 

라는 코드가 있다고 하면, 직접 실행할 경우에는

example_module is being run directly.
Hello! This function is in example_module.

 

다른 모듈에서 import할 경우에는

example_module has been imported.

 

가 출력되는 것이죠