Notice
Recent Posts
Recent Comments
Today
Total
05-04 00:14
Archives
관리 메뉴

Jeongchul Kim

Python 실행 시 Argument 받기 (sys.argv) 본문

카테고리 없음

Python 실행 시 Argument 받기 (sys.argv)

김 정출 2022. 12. 29. 16:17

Python 실행 시 Argument 받기 (sys.argv)

 

Python 스크립트 실행 시 인자값(Argument)을 전달받는 방법에 대해서 확인해보겠습니다.

https://docs.python.org/3/library/sys.html#sys.argv/ 

sys.argv
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.

sys 라이브러리를 Import 해야 합니다.
argv의 0번째 값은 스크립트 이름입니다. 우리가 받는 Argument는 1번째 인덱스부터 시작입니다.
2개의 Argument를 전달받는 예제입니다.

  • 파일 경로: file_path
  • 파일 타입: file_type
import sys

# argv의 길이를 먼저 확인합니다.
if len(sys.argv) != 3:
  print('Insufficient program arguments [FILE_PATH], [FILE_TYPE]')
  sys.exit(1)

for idx, arg in enumerate(sys.argv):
  print('arg [%d] %s' % (idx, arg))

file_path = sys.argv[1]
file_type = sys.argv[2]
print('file_path=', file_path)
print('file_type=', file_type)

정상적으로 Arguments를 2개 입력했을 시 

감사합니다.

Comments