[Python] Argument Parsing

미남잉·2025년 2월 26일
0

Advanced Python

목록 보기
4/10

  • Access system-specific parameters and functions.
  • Give information about constants, functions, and methods of the interpreter.
  • Command-line Arguments in Python sys Module
  • Changing the Output Behavior of the Shell
  • Ways to Read and Write in Python sys Module
  • Investigating the Path in Python sys Module
import sys

# Usage: main.py FILENAME MESSAGE
filename = sys.argv[1]
message = sys.argv[2]

with open(filename, 'w+') as f:
    f.write(message)

코드 분석

  1. import sys
    • sys 모듈을 불러와서 명령줄 인자를 받을 수 있도록 함.
  2. filename = sys.argv[1]
    • 첫 번째 명령줄 인자(sys.argv[1])를 filename 변수에 저장함.
    • 실행 시 첫 번째 인자로 파일 이름을 받음.
  3. message = sys.argv[2]
    • 두 번째 명령줄 인자(sys.argv[2])를 message 변수에 저장함.
    • 실행 시 두 번째 인자로 파일에 저장할 메시지를 받음.
  4. with open(filename, 'w+') as f:
    • 주어진 filename으로 파일을 w+(쓰기 및 읽기 모드)로 열거나 생성함.
    • 기존 파일이 있다면 내용을 덮어씀.
    • f.write(message)
    • 파일에 message 내용을 씀.

실행 예시

터미널에서 다음과 같이 실행하면:

python [main.py](http://main.py/) test.txt "Hello World"

위 코드는 test.txt 파일을 생성하고, 그 안에 "Hello World"를 저장함.

결과

  • 실행할 때 인자로 받은 파일 이름으로 새 파일을 만들거나 기존 파일을 덮어씀.
  • 인자로 받은 메시지를 해당 파일에 저장함.

주의할 점

  • sys.argv[1], sys.argv[2]를 직접 참조하기 때문에 실행할 때 최소한 두 개의 인자를 넘겨야 함.
  • 기존 파일이 있을 경우 내용이 지워질 수 있음
profile
Computer Vision Engineer

0개의 댓글

관련 채용 정보