argparse_example.py
· 775 B · Python
Исходник
import argparse
# 建立參數解析器物件
parser = argparse.ArgumentParser(description='這是一個範例程式,使用 argparse 模組解析命令列參數')
# 添加位置參數
parser.add_argument('input_file', help='輸入檔案的路徑')
# 添加選擇性參數
parser.add_argument('-o', '--output', help='輸出檔案的路徑')
# 添加開關參數
parser.add_argument('-v', '--verbose', action='store_true', help='啟用詳細模式')
# 解析命令列參數
args = parser.parse_args()
# 使用解析後的參數進行相應的處理
input_file = args.input_file
output_file = args.output
verbose_mode = args.verbose
# 輸出相關訊息
print('輸入檔案:', input_file)
print('輸出檔案:', output_file)
print('詳細模式:', verbose_mode)
| 1 | import argparse |
| 2 | |
| 3 | # 建立參數解析器物件 |
| 4 | parser = argparse.ArgumentParser(description='這是一個範例程式,使用 argparse 模組解析命令列參數') |
| 5 | |
| 6 | # 添加位置參數 |
| 7 | parser.add_argument('input_file', help='輸入檔案的路徑') |
| 8 | |
| 9 | # 添加選擇性參數 |
| 10 | parser.add_argument('-o', '--output', help='輸出檔案的路徑') |
| 11 | |
| 12 | # 添加開關參數 |
| 13 | parser.add_argument('-v', '--verbose', action='store_true', help='啟用詳細模式') |
| 14 | |
| 15 | # 解析命令列參數 |
| 16 | args = parser.parse_args() |
| 17 | |
| 18 | # 使用解析後的參數進行相應的處理 |
| 19 | input_file = args.input_file |
| 20 | output_file = args.output |
| 21 | verbose_mode = args.verbose |
| 22 | |
| 23 | # 輸出相關訊息 |
| 24 | print('輸入檔案:', input_file) |
| 25 | print('輸出檔案:', output_file) |
| 26 | print('詳細模式:', verbose_mode) |
| 27 | |
| 28 |