はじめに
Python の argparse モジュールは、アプリケーションのコマンドラインインターフェイス (CLI) を構築するための強力なツールです。このチュートリアルでは、位置引数 (positional arguments) とオプション引数 (optional arguments) の違いを探り、柔軟で使いやすい Python プログラムを作成するためにこれらをどのように効果的に利用するかを学びます。
Python の argparse モジュールは、アプリケーションのコマンドラインインターフェイス (CLI) を構築するための強力なツールです。このチュートリアルでは、位置引数 (positional arguments) とオプション引数 (optional arguments) の違いを探り、柔軟で使いやすい 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 が自動的にエラーメッセージを生成することに注目してください。
次のステップでは、引数の 2 つの主要なタイプ、位置引数 (positional) とオプション引数 (optional) について詳しく調べます。
位置引数 (Positional arguments) は 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 パラメータは、ユーザーが定義した演算のみを使用できるようにし、無効な演算を使用しようとしたときに役立つエラーメッセージを提供します。
位置引数は、プログラムを実行するために欠かせない必須入力に最適です。しかし、時には必須ではないオプションやデフォルト値を持つオプションを提供する必要があります。そこで登場するのがオプション引数で、次のステップで詳しく見ていきます。
オプション引数 (Optional arguments) は、コマンドラインインターフェイスに柔軟性をもたらします。位置引数 (Positional arguments) とは異なり、オプション引数は以下の特徴を持ちます。
-、長い形式は --)オプション引数の使用を示すプログラムを作成してみましょう。
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 となります。
オプション引数は、コマンドラインインターフェイスをより柔軟で使いやすくします。ユーザーは、毎回すべての情報を提供する必要なく、プログラムの動作をカスタマイズすることができます。
次のステップでは、位置引数とオプション引数を 1 つのプログラムで組み合わせる方法を見ていきます。
ほとんどの高度なコマンドラインプログラムは、位置引数 (Positional arguments) とオプション引数 (Optional arguments) を組み合わせて使用しています。位置引数は、プログラムが必要とする必須入力に最適です。一方、オプション引数は柔軟性と設定オプションを提供します。
両方のタイプの引数を効果的に組み合わせる方法を示すファイル処理プログラムを作成してみましょう。
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
位置引数とオプション引数を組み合わせる際には、以下のガイドラインを念頭に置いてください。
位置引数とオプション引数を効果的に組み合わせることで、強力で使いやすいコマンドラインインターフェイスを作成することができます。
この実験 (Lab) では、Python の argparse モジュールにおける位置引数 (Positional arguments) とオプション引数 (Optional arguments) の基本的な違いを学びました。
位置引数 (Positional arguments) は、コマンドラインでの位置によって定義される必須入力です。プログラムを実行するために必要な重要な情報に最適です。
オプション引数 (Optional arguments) はハイフンで始まり、省略可能です。プログラムに柔軟性と設定オプションを提供します。
argparse を使用して使いやすいコマンドラインインターフェイスを構築する方法を示すいくつかの Python プログラムを作成しました。以下のことを学びました。
これらのスキルは、コマンドラインから実行できる、より柔軟で使いやすい Python アプリケーションを作成するのに役立ちます。単純なユーティリティを構築する場合でも、複雑なアプリケーションを構築する場合でも、argparse はコマンドライン引数を処理するための強力なフレームワークを提供します。