소개
Python 의 argparse 모듈은 애플리케이션을 위한 명령줄 인터페이스 (CLI) 를 구축하는 강력한 도구입니다. 이 튜토리얼에서는 위치 인자와 선택적 인자의 차이점을 살펴보고, 유연하고 사용자 친화적인 Python 프로그램을 효과적으로 만들기 위해 어떻게 활용하는지 알아보겠습니다.
Python 의 argparse 모듈은 애플리케이션을 위한 명령줄 인터페이스 (CLI) 를 구축하는 강력한 도구입니다. 이 튜토리얼에서는 위치 인자와 선택적 인자의 차이점을 살펴보고, 유연하고 사용자 친화적인 Python 프로그램을 효과적으로 만들기 위해 어떻게 활용하는지 알아보겠습니다.
Python 의 argparse 모듈은 애플리케이션을 위한 명령줄 인터페이스 (CLI) 를 생성하는 강력한 도구입니다. 이 모듈을 사용하면 명령줄 인수를 정의하고 구문 분석하여 사용자 입력을 처리하고 프로그램의 동작을 사용자 정의하는 것이 더 쉬워집니다.
이 단계에서는 argparse 모듈의 기본 사항을 배우고 첫 번째 간단한 명령줄 프로그램을 만들어 보겠습니다.
명령줄에서 Python 스크립트를 실행할 때, 스크립트가 어떻게 동작해야 하는지 추가 정보를 제공하거나 구성해야 하는 경우가 많습니다. argparse 모듈은 다음을 수행하는 편리한 방법을 제공합니다.
argparse의 기본 사항을 이해하기 위해 간단한 예제를 만들어 보겠습니다.
WebIDE 에서 /home/labex/project 디렉토리에 hello_argparse.py라는 새 파일을 만듭니다.
다음 코드를 파일에 추가합니다.
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A simple greeting program")
## Add a name argument
parser.add_argument("name", help="The name to greet")
## Parse the arguments
args = parser.parse_args()
## Use the arguments in our program
print(f"Hello, {args.name}!")
파일을 저장합니다.
터미널을 열고 이름을 인수로 사용하여 프로그램을 실행합니다.
python /home/labex/project/hello_argparse.py Alice
Hello, Alice!
python /home/labex/project/hello_argparse.py
usage: hello_argparse.py [-h] name
hello_argparse.py: error: the following arguments are required: name
이 기본 예제는 argparse가 어떻게 작동하는지 보여줍니다. 입력을 이름으로 받고 인사를 출력하는 간단한 프로그램을 정의했습니다. argparse가 필요한 인수를 제공하지 않으면 자동으로 오류 메시지를 생성하는 것을 확인하십시오.
다음 단계에서는 두 가지 주요 유형의 인수, 즉 위치 인자와 선택적 인수에 대해 자세히 알아보겠습니다.
위치 인자는 argparse에서 가장 간단한 유형의 인수입니다. 명령줄에서의 위치에 따라 의미가 결정되기 때문에 "위치"라고 불립니다.
- 또는 --) 를 사용하지 않습니다.기본 산술 연산을 수행하는 위치 인자를 사용하는 프로그램을 만들어 보겠습니다.
WebIDE 에서 /home/labex/project 디렉토리에 calculator.py라는 새 파일을 만듭니다.
다음 코드를 파일에 추가합니다.
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A simple calculator")
## Add positional arguments
parser.add_argument("operation", help="The operation to perform (add, subtract, multiply, divide)")
parser.add_argument("x", type=float, help="The first number")
parser.add_argument("y", type=float, help="The second number")
## Parse the arguments
args = parser.parse_args()
## Perform the calculation based on the operation
if args.operation == "add":
result = args.x + args.y
elif args.operation == "subtract":
result = args.x - args.y
elif args.operation == "multiply":
result = args.x * args.y
elif args.operation == "divide":
if args.y == 0:
print("Error: Cannot divide by zero")
exit(1)
result = args.x / args.y
else:
print(f"Error: Unknown operation '{args.operation}'")
print("Valid operations are: add, subtract, multiply, divide")
exit(1)
## Display the result
print(f"Result: {result}")
파일을 저장합니다.
다른 연산으로 프로그램을 실행합니다.
python /home/labex/project/calculator.py add 5 3
Result: 8.0
python /home/labex/project/calculator.py multiply 4 7
출력:
Result: 28.0
다양한 방식으로 위치 인자를 사용자 정의할 수도 있습니다.
nargs를 사용하여 여러 값을 허용합니다.default를 사용하여 기본값을 제공합니다.choices를 사용하여 값을 선택 집합으로 제한합니다.연산에 choices 매개변수를 포함하도록 계산기를 수정해 보겠습니다.
WebIDE 에서 calculator.py를 엽니다.
choices 매개변수를 포함하도록 연산 인수를 수정합니다.
parser.add_argument("operation",
choices=["add", "subtract", "multiply", "divide"],
help="The operation to perform")
파일을 저장합니다.
유효한 연산으로 프로그램을 실행합니다.
python /home/labex/project/calculator.py add 5 3
Result: 8.0
python /home/labex/project/calculator.py power 2 3
usage: calculator.py [-h] {add,subtract,multiply,divide} x y
calculator.py: error: argument operation: invalid choice: 'power' (choose from 'add', 'subtract', 'multiply', 'divide')
choices 매개변수는 사용자가 정의한 연산만 사용할 수 있도록 보장하고, 유효하지 않은 연산을 사용하려고 할 때 유용한 오류 메시지를 제공합니다.
위치 인자는 프로그램이 없이는 실행될 수 없는 필수 입력에 적합합니다. 그러나 때로는 필수적이지 않거나 기본값이 있는 옵션을 제공해야 합니다. 다음 단계에서 살펴볼 선택적 인수가 바로 그 경우입니다.
선택적 인자는 명령줄 인터페이스에서 유연성을 제공합니다. 위치 인자와 달리 선택적 인자는 다음과 같습니다.
-, 긴 형식은 --).선택적 인수의 사용을 보여주는 프로그램을 만들어 보겠습니다.
WebIDE 에서 /home/labex/project 디렉토리에 greeting.py라는 새 파일을 만듭니다.
다음 코드를 파일에 추가합니다.
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A customizable greeting program")
## Add optional arguments
parser.add_argument("-n", "--name", default="World", help="The name to greet (default: World)")
parser.add_argument("-g", "--greeting", default="Hello", help="The greeting to use (default: Hello)")
parser.add_argument("-c", "--count", type=int, default=1, help="Number of times to display the greeting (default: 1)")
## Parse the arguments
args = parser.parse_args()
## Display the greeting
for _ in range(args.count):
print(f"{args.greeting}, {args.name}!")
파일을 저장합니다.
인수가 없이 프로그램을 실행합니다.
python /home/labex/project/greeting.py
Hello, World!
python /home/labex/project/greeting.py --name Alice --greeting Hi
Hi, Alice!
python /home/labex/project/greeting.py -n Bob -g Hey -c 3
Hey, Bob!
Hey, Bob!
Hey, Bob!
argparse는 여러 유형의 선택적 인수를 지원합니다.
플래그 인수 (Flag arguments): 존재하거나 존재하지 않는 부울 플래그입니다.
값을 가진 인수 (Arguments with values): 값을 사용하는 선택적 인수입니다.
인사 프로그램에 플래그 인수를 포함하도록 수정해 보겠습니다.
WebIDE 에서 greeting.py를 엽니다.
대문자 플래그에 대한 플래그 인수를 추가합니다.
import argparse
## Create an argument parser
parser = argparse.ArgumentParser(description="A customizable greeting program")
## Add optional arguments
parser.add_argument("-n", "--name", default="World", help="The name to greet (default: World)")
parser.add_argument("-g", "--greeting", default="Hello", help="The greeting to use (default: Hello)")
parser.add_argument("-c", "--count", type=int, default=1, help="Number of times to display the greeting (default: 1)")
parser.add_argument("-u", "--uppercase", action="store_true", help="Display the greeting in uppercase")
## Parse the arguments
args = parser.parse_args()
## Create the greeting message
message = f"{args.greeting}, {args.name}!"
## Convert to uppercase if requested
if args.uppercase:
message = message.upper()
## Display the greeting
for _ in range(args.count):
print(message)
파일을 저장합니다.
대문자 플래그로 프로그램을 실행합니다.
python /home/labex/project/greeting.py -n Charlie -u
HELLO, CHARLIE!
action="store_true" 매개변수는 플래그가 값을 사용하지 않음을 의미합니다. 즉, 존재하거나 (True) 존재하지 않습니다 (False).
선택적 인수는 명령줄 인터페이스를 더 유연하고 사용자 친화적으로 만듭니다. 사용자가 매번 모든 정보를 제공할 필요 없이 프로그램의 동작을 사용자 정의할 수 있습니다.
다음 단계에서는 위치 인자와 선택적 인수를 단일 프로그램에서 결합하는 방법을 살펴보겠습니다.
대부분의 정교한 명령줄 프로그램은 위치 인자와 선택적 인자를 함께 사용합니다. 위치 인자는 프로그램에 필요한 필수 입력에 적합하며, 선택적 인자는 유연성과 구성 옵션을 제공합니다.
두 유형의 인수를 효과적으로 결합하는 방법을 보여주는 파일 처리 프로그램을 만들어 보겠습니다.
WebIDE 에서 /home/labex/project 디렉토리에 file_processor.py라는 새 파일을 만듭니다.
다음 코드를 파일에 추가합니다.
import argparse
import os
## Create an argument parser
parser = argparse.ArgumentParser(description="A file processing utility")
## Add positional arguments
parser.add_argument("filename", help="The file to process")
## Add optional arguments
parser.add_argument("-c", "--count", action="store_true", help="Count lines in the file")
parser.add_argument("-s", "--search", help="Search for a string in the file")
parser.add_argument("-o", "--output", help="Output results to this file instead of console")
parser.add_argument("-v", "--verbose", action="store_true", help="Display detailed information")
## Parse the arguments
args = parser.parse_args()
## Check if the file exists
if not os.path.isfile(args.filename):
print(f"Error: The file '{args.filename}' does not exist.")
exit(1)
## Process the file
results = []
## Display verbose information if requested
if args.verbose:
print(f"Processing file: {args.filename}")
print(f"File size: {os.path.getsize(args.filename)} bytes")
## Open and process the file
with open(args.filename, 'r') as file:
content = file.readlines()
## Count lines if requested
if args.count:
line_count = len(content)
results.append(f"Line count: {line_count}")
## Search for string if requested
if args.search:
matching_lines = [line for line in content if args.search in line]
match_count = len(matching_lines)
results.append(f"Found '{args.search}' in {match_count} lines:")
results.extend(matching_lines)
## Output the results
output_text = '\n'.join(results)
if args.output:
## Write to output file
with open(args.output, 'w') as output_file:
output_file.write(output_text)
if args.verbose:
print(f"Results written to {args.output}")
else:
## Print to console
print(output_text)
파일을 저장합니다.
이제 처리할 샘플 텍스트 파일을 만들어 보겠습니다.
echo -e "This is line 1\nThis is line 2\nThis is line 3\nPython is awesome\nArgparse makes CLI easy" > /home/labex/project/sample.txt
python /home/labex/project/file_processor.py /home/labex/project/sample.txt
선택적 인수로 작업을 지정하지 않았으므로 출력이 표시되지 않습니다.
python /home/labex/project/file_processor.py /home/labex/project/sample.txt --count
Line count: 5
python /home/labex/project/file_processor.py /home/labex/project/sample.txt --search "line"
Found 'line' in 3 lines:
This is line 1
This is line 2
This is line 3
python /home/labex/project/file_processor.py /home/labex/project/sample.txt --count --search "Python" --verbose
Processing file: /home/labex/project/sample.txt
File size: 96 bytes
Line count: 5
Found 'Python' in 1 lines:
Python is awesome
python /home/labex/project/file_processor.py /home/labex/project/sample.txt --count --search "is" --output /home/labex/project/results.txt --verbose
Processing file: /home/labex/project/sample.txt
File size: 96 bytes
Results written to /home/labex/project/results.txt
cat /home/labex/project/results.txt
Line count: 5
Found 'is' in 5 lines:
This is line 1
This is line 2
This is line 3
Python is awesome
Argparse makes CLI easy
위치 인자와 선택적 인수를 결합할 때는 다음 지침을 염두에 두십시오.
위치 인자와 선택적 인수를 효과적으로 결합하면 강력하고 사용자 친화적인 명령줄 인터페이스를 만들 수 있습니다.
이 랩에서는 Python 의 argparse 모듈에서 위치 인자와 선택적 인자의 근본적인 차이점을 배웠습니다.
**위치 인자 (Positional arguments)**는 명령줄에서의 위치에 의해 정의되는 필수 입력입니다. 프로그램 실행에 필요한 필수 정보에 이상적입니다.
**선택적 인자 (Optional arguments)**는 하이픈으로 시작하며 생략할 수 있습니다. 프로그램에 유연성과 구성 옵션을 제공합니다.
argparse 를 사용하여 사용자 친화적인 명령줄 인터페이스를 구축하는 방법을 보여주는 여러 Python 프로그램을 만들었습니다. 다음 방법을 배웠습니다.
이러한 기술은 명령줄에서 실행할 수 있는 더 유연하고 사용자 친화적인 Python 응용 프로그램을 만드는 데 도움이 될 것입니다. 간단한 유틸리티를 구축하든 복잡한 응용 프로그램을 구축하든, argparse 는 명령줄 인수를 처리하기 위한 강력한 프레임워크를 제공합니다.