[Python] Python Script File 실행해보기

2023. 6. 9. 22:31·Programming
728x90
728x90

1. Python Script File (=main script file)의 구조

다음은 일반적인 Python script file의 전형적인 구조를 간략히 나타냄. (고정된 것은 아님.)

  1. 이미 구현된 기능 등을 사용하기 위해 외부 library 와 module을 import함.
  2. 코드의 재사용성과 가독성 등을 위해 반복되는 code들을 function이나 class로 정의.
  3. main script (=main program)으로 동작하는 경우에 수행될 script에 해당하는 main function 작성.
    • 일반적으로 main 함수는 초기화 및 user input에 대한 처리 등으로 시작.
    • 이후 입력된 data들에 대해 processing을 수행 (2번에 정의한 function 및 class의 instance사용)
    • 처리 결과 등을 출력하고 적절한 return value를 반환하고 종료.
  4. main script로만 동작할 경우에는 main함수를 호출하여 수행하도록 처리.
    • __name__ 변수(=special or magic or dunder variable이라고 불림)가
    • "__main__" 의 문자열 값을 가지는 경우 main 함수 호출!

1-1. main script vs. module

  • 위와 같이 python interpreter에 경로를 넘겨주어 직접 수행되는 python script file을 main script 라고 부름.
  • 반면, import되어 사용되는 python code file들은 module이라고 부름.

주의할 것은 module 이면서 main script로도 동작가능한 경우, main 이라는 이름의 함수를 가지는 경우가 많음: main 함수를 entry point라고 부름.

Python Source Code 파일 하나가
하나의 module이라고 볼 수 있음.

단, import가 되지 못하는 python source code 파일의 경우에는 module이라고 부르기 보다는 main script file (줄여서 script)라고도 부르는 경우가 많음.

 

Module 에 대한 개념을 다음을 참고: https://dsaint31.me/mkdocs_site/python/basic/module_package/

 

BME228

Modules and Packages Module 쉽게 생각하면 Python code 로 구성된 file을 가르킨다. Module은 import될 때 각각 고유의 namespace를 가짐 (Namespace의 역할도 수행). Python에서 module은 확장자가 .py인 파일을 가르킴 (py

dsaint31.me

Dunder(=double underscore) variable에 대한 개념은 다음을 참고: https://ds31x.tistory.com/129

 

[Python] __name__ : Special string variable

Python에서 module에 할당되는 special attributes 중 하나로서, 해당 module의 이름에 해당하는 문자열로 설정되어 있다. __name__은 Python이 알아서 생성해주는 special string attribute임. 하지만, module이 command lin

ds31x.tistory.com


1-2. module (Python code file)을 실행하기 (main script로)

 

다음 Example에서 살펴보겠지만 크게 2가지 방법으로 실행시킴.

  • Python Interpreter 프로그램에 argument로 실행시킬 python code file의 path를 넘겨주어 실행.
  • Python Interpreter 프로그램에 -m (--module) 옵션을 주고, 실행하고자 하는 module 명을 넘겨주어 실행.
    • 이 경우에는 Python Interpreter가 module 이름으로 해당하는 file을 찾을 수 있어야함.
    • module search path 에 해당 module 이름에 해당하는 file이 있어야 한다: 자세한 건 앞서 module  참고 자료 url을 볼 것.
    • 일반적으로 working directory는 기본적으로 python interpreter가 모듈을 찾는 경로에 포함됨.

잘 사용되지 않지만 또 다른 실행 방법은 -i (=interactive) 옵션으로 실행할 Python Code File의 Path를 넘겨주는 것으로, 이 경우 해당 python code file 을 실행하고나서 interactive mode로 들어가게 된다.

 


2. Example

위의 순서를 따르는 예제 Python script는 아래에 있음. (파일명 : py_hello_python.py)

해당 script는
원의 반지름 값을 argument로 입력받아,
해당 반지름을 가지는 원의 넓이를 계산하여
출력해 주는 프로그램임.

# py_hello_pyton.py 

# import necessary libraries
import sys   # to get arguments
import math  # to get pi

# define functions
def get_circle_area(r):
    return math.pi * r **2

def main():
    # initialization and get user's input
    radius = 0.
    area = 0.
    args = sys.argv

    # processing
    argc = len(args)
    if argc > 1:
        radius = float(args[1])

    area = get_circle_area(radius)

    # print result! 
    print (f'Hello, Python!')
    print (f'The area of a circle with a radius of {radius} is {area}')

    return 0

# __name__ is a special string attribute
# that distinguishes whether 
#  * the current module (=py file) is imported from another module 
#  * or is directly executed as the main script
# , and the Python interpreter sets 
#            the value of __name__ for all modules.
if __name__ == "__main__":
    # Code that only runs when it is executed as the main script.
    main()

2-1. example 실행하기 (main script 파일의 path 이용)

해당 python 파일(py_hello_pyton.py)을 python interpreter로 수행하는 명령어와 결과는 다음과 같음.

$python py_hello_python.py 4
Hello, Python!
The area of circle having radius of 4.0 = 50.26548245743669

2-2. example 실행하기 (-m 옵션사용하기)

python interpreter에 -m 옵션으로 수행할 수 있음. 이 경우 해당 option을 통해 수행될 module명을 지정해 준다.

$python -m py_hello_python 3
hello_python 3
Hello, Python!
The area of a circle with a radius of 3.0 is 28.274333882308138

 


3. Python Virtual Machine (PVM) based Python Interpreter 

다음 그림은 Python Interpreter에서 python program이 실행되는 순서에 대한 diagram임.

위의 Python Source Code는 Python Interpreter에서

  • bytecode로 변환이 되며,
  • 해당 bytecode는 source code가 있는 디렉터리에 있는 __pycache__ 서브디렉터리 내에 저장된다.
  • 해당 bytecode는 source code와 이름이 같고, 표준 Python Interpreter인 CPython을 사용할 경우 .pyc의 확장자를 가진다.

위의 script에선 math와 sys module을 사용하여 기존의 구현된 기능을 사용하였다.

  • Python Interpreter를 설치할 때 같이 제공되는 built-in module들임.

bytecode 참고자료: https://dsaint31.me/mkdocs_site/CE/ch08/ce08_compiler_interpreter/#byte-code

 

BME228

Compiler Language and Interpreter Language Compiler Language Compiler(High-level language를 machine language로 번역)를 사용하는 고급 언어. 프로그램 전체를 읽어들여 이를 object code(목적코드)로 바꿈. Compiler 능력에 따

dsaint31.me

Binary code 참고자료: https://dsaint31.me/mkdocs_site/CE/ch08/ce08_compiler_interpreter/#binary-code

 

BME228

Compiler Language and Interpreter Language Compiler Language Compiler(High-level language를 machine language로 번역)를 사용하는 고급 언어. 프로그램 전체를 읽어들여 이를 object code(목적코드)로 바꿈. Compiler 능력에 따

dsaint31.me


3.1 PVM

Python Virtual Machine은

  • 이 bytecode를 Host OS에서 수행가능한 binary code, 즉 machine code로 바꾸어서
  • Host system에서 수행되도록 한다.
  • Virtual Machine들은 자신의 고유한 instruction set을 가지고 있음 (instruction = binary code = machine code)
Virtual machine 
an abstract computer with an incredibly complicated instruciton set
implemented entirely in software.

2023.06.05 - [Programming] - [Python] Interpreter and PVM (Python Virtual Machine)

 

[Python] Interpreter and PVM (Python Virtual Machine)

Interpreter and PVM (Python Virtual Machine)더보기대학을 막 졸업해서 초보 프로그래머로 일을 할 때 개인적으로 가지고 있던 편견 중 하나가 script language를 매우 하찮게 생각하면서 오직 compiler language

dsaint31.tistory.com


4. 다른 실행방법: REPL, Python Interactive Shell

이 예제와 같이 .py 파일을 통째로 Python Interpreter에 넘겨주어 해당 파일의 코드들을 한번에 실행할 수도 있지만, Python (Interactive) Shell을 통해 REPL 모드로 수행할 수도 있다.

  • 이 경우엔 enter를 통해 statement 입력이 끝났음을 Python shell에 알려주면
  • python shell은 입력된 statement를 Python interpreter에 읽어들이고(Read)시키고
  • 수행한 결과를 얻어(Evaluation), 출력(Print)하고 다시 입력을 대기하는 것을 반복(Loop)한다.
  • 참고로 exit() statement가 입력될 경우 python shell은 종료함.

앞서 다룬 -i 옵션 (script실행 후 interactive mode로 전환) 은 .py 파일을 통째로 실행시키면서 동시에 interactive mode로 전환하는 일종의 하이브리드 실행 모드임: 주로 디버깅 등에 많이 이용되거나, 환경 설정 등을 .py 파일로 하고 나서 interacitve한 처리가 필요할 때 사용됨.

 

Interactive mode로 실행에 대한 보다 자세한 자료:2023.06.09 - [Programming] - [Python] Python Interactive Shell (or Python Interactive Prompt)

 

[Python] Python Interactive Shell (or Python Interactive Prompt)

REPL or Interactive Mode Python을 가장 쉽게 (또는 naive하게) 사용하는 방법은 Python Shell을 통해 사용하는 것임. 이 경우, Python Interpreter는 사용자가 Python Shell의 prompt에 입력한 statement 단위로 수행을 시키

dsaint31.tistory.com


5. 또다른 실행방법: -c 옵션(command)을 사용한 inline 실행.

마지막으로 inline 실행방법이 있음 (Shell Programming 등과 같이 사용될 때 이용됨)

 

-c (command)옵션을 이용하여 실행시킬 python 코드의 문자열을 직접 넘겨주어 실행하는 방법.

자동화 작업 등을 위해 shell script에서 사용되거나 빠른 테스트 등에 사용됨.

#!/bin/bash

# python -c 결과를 Shell 변수로 저장
result=$(python -c "print(10 + 20)")

# 결과 출력
echo "Python 결과: $result"

 

위의 코드에서 $(~) 은 command substitution 으로 parentheses 안의 명령어의 출력결과로 치환되는 shell programming의  기능 중 하나임. command substituion 에 대한 자세한 것은 다음 URL을 참고:

https://ds31x.tistory.com/113

 

[Shell] command substitution

command substitution (명령어치환)우리나라말로 명령어 치환 이라고 불리며,특정 명령어의 수행결과를 문자열로 입력받는 형태로 셀프로그래밍 등에서 사용됨.command substitution 사용법아래 예제는 resu

ds31x.tistory.com

  • Windows 의 cmd에선 command substitution을 backtick ` 만을 지원함.
  • 위와 같은 $(~)를 쓰려면 PowerShell을 이용해야 한다.
  • 사실 inline 으로의 수행은 거의 서버 장비에서 활용하는 터라... bash 와 같이 사용한 경험 뿐인지라 cmd는 ... (zsh까지가 마지노선이 아닐까 싶다.)

 

'Programming' 카테고리의 다른 글

[Python] Function Definition, Call and Arguments  (0) 2023.06.10
[Python] Python Interactive Shell (or Python Interactive Prompt)  (0) 2023.06.09
[Programming] Application Programming Interface (API)  (0) 2023.06.08
[Python] range and enumerate  (0) 2023.06.07
[Python] Iterable and Iterator, plus Generator  (1) 2023.06.07
'Programming' 카테고리의 다른 글
  • [Python] Function Definition, Call and Arguments
  • [Python] Python Interactive Shell (or Python Interactive Prompt)
  • [Programming] Application Programming Interface (API)
  • [Python] range and enumerate
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (742)
      • Private Life (13)
      • Programming (188)
        • DIP (106)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    numpy
    math
    DIP
    SS
    Programming
    signals_and_systems
    fourier transform
    opencv
    SIGNAL
    Optimization
    function
    random
    인허가제도
    Term
    Probability
    linear algebra
    Vector
    Python
    signal_and_system
    Convolution
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] Python Script File 실행해보기
상단으로

티스토리툴바