Computer Language/Python

[Python] main.py 의 if __name__ == '__main__' 이해하기

꽁담 2023. 4. 8. 15:58

Pycharm 의 main.py

Pycharm 에서 프로젝트를 생성하면 main.py 가 생성됩니다.

다만 이는 main.py 를 만든다는 옵션을 선택하는 경우에 입니다.

 

main.py 의 코드를 보면 아래와 같습니다.

아래에서 좀 더 자세히 다룰 예정입니다.

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

main.py 실행하기

우측의 재생(실행)버튼을 클릭하면 main.py 가 실행됩니다.

그리고 결과로 Hi, Pycharm 이 출력됩니다.

 

 

main.py 실행 이해하기

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

 

def 는 함수를 정의합니다.

print_hi 의 함수명과 외부에서 이 함수를 호출할 때 파라미터로 값을 받아 name 변수에 저장합니다.

print_hi 함수내에서는 print 함수를 통해 Hi 문자열과 name 변수 문자열을 더해 출력합니다.

if __name__ == '__main__':
    print_hi('PyCharm')

__name__ 절은 내부에서 사용하는 특별한 변수로, __main__ 은 현재 파일이 프로그램의 시작점이 맞는지 판단합니다.

즉, 메인 프로그램을 사용할 지 모듈로 사용할지를 구분하기 위한 용도입니다.

 

위의 경우 print_hi 함수를 실행하도록 되어있고, print_hi 함수는 위의 def 에 정의되어 있습니다.

 

 

Python 이 실행되는 방법 두 가지

참고로 파이썬이 프로그램을 실행하는 방법은 두 가지로 나뉩니다.

 

모듈로 실행되는가 ?

모듈로 실행하는 경우, 모듈의 명칭이 __name__ 변수에 할당됩니다.

모듈은 이 후에 다루겠습니다.

 

메인으로 실행되는가 ?

위의 코드처럼 main 을 정의합니다.

 

 

기타

 

__main__ 이 아니라면 ?

__main__ 인 경우와 __main__ 이 아닌 경우를 비교해 보겠습니다.

__name__ 변수에 main 도 아니고, 모듈이 있지도 않기 때문에 실행되지 않습니다.

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
print('Step1')
if __name__ == '__main__':
    print_hi('PyCharm')
print('Step2')
if __name__ == '__Notmain__':
    print_hi('PyCharm Not Main')
print('Step3')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

파이썬은 C / JAVA 처럼 main 시작점이 없다.

파이썬은 리눅스/유닉스 스크립트 언어 기반입니다.

따라서 파일의 위에서부터 실행하며 프로그램의 시작점이 정해져 있지 않습니다.