python argparse變量到class變量的轉換代碼

  github上的項目總喜歡使用argparse + bash來運行,這對於快速運行一個項目來說可能有好處,但在debug的時候是很難受的。因爲我們需要在.sh文件中修改傳入參數,並且不能使用jupyter。

  以下是把parser轉換成顯式class命名空間的一個代碼示例:

#%%
import argparse

parser = argparse.ArgumentParser()
 
parser.add_argument("--get_pred",
                    action='store_true',
                    help="Whether to get prediction results.")
parser.add_argument("--get_ig_pred",
                    action='store_true',
                    help="Whether to get integrated gradient at the predicted label.")
parser.add_argument("--get_ig_gold",
                    action='store_true',
                    help="Whether to get integrated gradient at the gold label.")
parser.add_argument("--get_base",
                    action='store_true',
                    help="Whether to get base values. ")
parser.add_argument("--batch_size",
                    default=16,
                    type=int,
                    help="Total batch size for cut.")
parser.add_argument("--num_batch",
                    default=10,
                    type=int,
                    help="Num batch of an example.")

#%% 轉換
def print_store_actions(store_actions, print_attrs = ['type', 'help'], need_default = True):
    if len(print_attrs) > 0:
        s = '# '
        for i in store_actions.__dir__():
            if i in print_attrs:
                s0 = str(getattr(store_actions, i))
                s0 = s0.replace('\n', ' ')
                s += s0 + ', '
        print(s[:-2])
    if need_default:
        if getattr(store_actions, 'type') == str:
            s = '# default = "' + str(getattr(store_actions, 'default')) + '"'
        else:
            s = '# default = ' + str(getattr(store_actions, 'default'))
        print(s)

def parser_2_class(parser, print_attrs = ['type', 'help'], need_default = True):
    for i in parser._actions:
        if i.option_strings[0] == '-h':
            continue
        v = '"' + i.default + '"' if i.type == str else i.default
        if len(print_attrs) == 0:
            print(i.option_strings[0][2:], '=', v, end='  ')
            print_store_actions(i, print_attrs, need_default)
        else:
            print_store_actions(i, print_attrs, need_default)
            print(i.option_strings[0][2:], '=', v)

parser_2_class(parser, ['type', 'help'], True)

  然後使用輸出構建一個只包含成員變量的類,就能實現和parser獲得的變量空間一樣的效果,從而可以方便地debug,並且無需修改項目的其它代碼。如下:

class args:
    # None, Whether to get prediction results.
    # default = False
    get_pred = False
    # None, Whether to get integrated gradient at the predicted label.
    # default = False
    get_ig_pred = False
    # None, Whether to get integrated gradient at the gold label.
    # default = False
    get_ig_gold = False
    # None, Whether to get base values. 
    # default = False
    get_base = False
    # <class 'int'>, Total batch size for cut.
    # default = 16
    batch_size = 16
    # <class 'int'>, Num batch of an example.
    # default = 10
    num_batch = 10

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章