Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 인수 구문 분석

<시간/>

모든 프로그래밍 언어에는 스크립트를 생성하고 터미널에서 실행하거나 다른 프로그램에서 호출하는 기능이 있습니다. 이러한 스크립트를 실행할 때 스크립트 내에서 실행되는 다양한 기능에 대해 스크립트에 필요한 인수를 전달해야 하는 경우가 많습니다. 이 기사에서는 인수를 파이썬 스크립트에 전달하는 다양한 방법이 무엇인지 알아볼 것입니다.

sys.argv 사용

이것은 내장 모듈 sys.argv가 스크립트와 함께 전달되는 인수를 처리할 수 있습니다. 기본적으로 sys.argv[0]에서 고려되는 첫 번째 인수는 파일 이름입니다. 나머지 인수는 1,2 등으로 인덱싱됩니다. 아래 예에서 스크립트가 전달된 인수를 사용하는 방법을 볼 수 있습니다.

import sys
print(sys.argv[0])
print("Hello ",sys.argv[1],", welcome!")

위의 스크립트를 실행하고 다음 결과를 얻기 위해 아래 단계를 수행합니다.

위의 코드를 실행하기 위해 터미널 창으로 이동하여 아래에 표시된 명령을 작성합니다. 여기서 스크립트 이름은 args_demo.py입니다. 이 스크립트에 값이 Samantha인 인수를 전달합니다.

D:\Pythons\py3projects>python3 args_demo.py Samantha
args_demo.py
Hello Samantha welcome!

getopt 사용

이것은 이전 접근 방식에 비해 더 많은 유연성을 가진 또 다른 접근 방식입니다. 여기에서 인수의 값을 수집하고 오류 처리 및 예외와 함께 처리할 수 있습니다. 아래 프로그램에서 인수를 취하고 파일 이름인 첫 번째 인수를 건너뛰어 두 숫자의 곱을 찾습니다. 물론 sys 모듈도 여기에 사용됩니다.

예시

import getopt
import sys

# Remove the first argument( the filename)
all_args = sys.argv[1:]
prod = 1

try:
   # Gather the arguments
   opts, arg = getopt.getopt(all_args, 'x:y:')
   # Should have exactly two options
   if len(opts) != 2:
      print ('usage: args_demo.py -x <first_value> -b <second_value>')
   else:
      # Iterate over the options and values
      for opt, arg_val in opts:
         prod *= int(arg_val)
      print('Product of the two numbers is {}'.format(prod))

except getopt.GetoptError:
   print ('usage: args_demo.py -a <first_value> -b <second_value>')
   sys.exit(2)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

D:\Pythons\py3projects >python3 args_demo.py -x 3 -y 12
Product of the two numbers is 36
# Next Run
D:\Pythons\py3projects >python3 args_demo.py
usage: args_demo.py -x <first_value> -b <second_value>

argparse 사용

이것은 실제로 추가 코드 줄 없이 모듈 자체에서 오류 및 예외를 처리하므로 인수 전달을 처리하는 데 가장 선호되는 모듈입니다. 사용할 모든 인수에 필요한 이름 도움말 텍스트를 언급한 다음 코드의 다른 부분에서 인수 이름을 사용해야 합니다.

예시

import argparse

# Construct an argument parser
all_args = argparse.ArgumentParser()

# Add arguments to the parser
all_args.add_argument("-x", "--Value1", required=True,
   help="first Value")
all_args.add_argument("-y", "--Value2", required=True,
   help="second Value")
args = vars(all_args.parse_args())

# Find the product
print("Product is {}".format(int(args['Value1']) * int(args['Value2'])))

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

D:\Pythons\py3projects>python3 args_demo.py -x 3 -y 21
Product is 63
# Next Run
D:\Pythons\py3projects>python3 args_demo.py -x 3 -y
usage: args_demo.py [-h] -x VALUE1 -y VALUE2
args_demo.py: error: argument -y/--Value2: expected one argument