為自己Coding
為自己Coding

YO~~ 剛跨入AI人工智慧領域的小小工程師, 熱愛自學, 熱愛分享, 下班後的我想為自己Coding, 積極撰寫教學文, 想將自學的程式知識分享給大家, 不斷追求進步的自己, 希望有一天能回饋社會,幫助需要幫助的人, 如果您有什麼很酷的想法,也覺得我還行,歡迎您找我合作~~ IG: https://www.instagram.com/coding_4_me/

Coding起來-Python- Argparse 簡易教學


Hi, 分享一個很好用的python 套件 Argparse,我看了一些網路上的教學,把它們整理了一下,簡單來說,它就是一個能讓我們在外部就能控制python內部變數的方法,過去我們可能改個變數就要到python檔裡改,但有了這個,我們可以easy在run python XXX.py指令時,就能輕鬆給予新的變數

Github連結

介紹

簡單介紹一下,在這個初始化的function下,可以設定的一些參數

這些參數都是可以自己隨便設定的 哈哈,但是為了要讓使用我們程式的人能懂在幹嘛,我們還是乖乖設定好

  1. prog: program name (程式名稱)
  2. usage: how to use your program (default=None, it will replace with your program name) (如何使用這個程式)
  3. description: describe about your program (介紹一下你的程式)
  4. epilog: additional materials (額外的參考文件)

範例:parser1 = ArgumentParser(prog = “my argparse example”, usage =None, description = “learn how to use argparse”,epilog = “https://github.com/chwang12341/Learn-Python-”)

實際操作

當然還是要實際play一下,大家就會使用了,很簡單當你想要把程式裡的變數改成外部控制時,你就parser.add_argument(名稱, 種類, 幫忙(當輸入錯的變數時就會跳出提醒,像是明明就應個是一個整數,然後使用的硬要放一個字串,這樣就不對了))

(ex.parser.add_argument(‘runtimes’, type=int, help=’display an integer’))


1.可選參數又是什麼

顧名思義就是你在run python檔的時候,可選擇添加或不添加的參數


2. 可選參數跟原本的方式(固定參數)差在哪?

原本:parser.add_argument(‘runtimes’, type=int, help=’display an integer’)

可選:parser.add_argument(‘ — place’, type=str, help=’display an integer’, dest = ‘position’)

沒錯,就是在第一個參數名稱前多一個 “ — “,哈哈


3. dest ?

當我們採用args(args = parser.parse_args())時

a.沒加dest的情況就是當我們要使用這個從外部傳回來的參數,我們會用args.place

ex.parser.add_argument(‘ — place’, type=str, help=’display an integer’)

b.而加了之後我們就會使用args.position

ex.parser.add_argument(‘ — place’, type=str, help=’display an integer’, dest = ‘position’)

其實就是解析過後,變數的名稱改成什麼


舉例:

Scenario: 今天我想寫一個PYTHON,我可以設定誰跑了幾次(固定參數),也可以設定在哪裡跑跟吃什麼(可選參數)

實際執行

有感受到這個套件方式很好用嗎 哈哈

當然它還有很多樣的用法!! 可以改變的參數也很多,可以參考它的官方文件

希望有幫助到您~~



Reference:

argparse - Parser for command-line options, arguments and sub-commands - Python 3.8.3 documentation
Source code: Lib/argparse.py The following code is a Python program that takes a list of integers and produces either…docs.python.org

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论