Última atividade 10 months ago

這段程式碼使用 Python 的 argparse 模組來解析命令列參數。它支援必填的位置參數(輸入檔案路徑)、選填的輸出檔案路徑(-o 或 --output),以及一個開關參數(-v 或 --verbose)來啟用詳細模式。這適用於 CLI 工具,使得用戶可以透過命令列提供不同的參數來控制程式行為。

timmy revisou este gist 10 months ago. Ir para a revisão

1 file changed, 27 insertions

argparse_example.py(arquivo criado)

@@ -0,0 +1,27 @@
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 +
Próximo Anterior