Python 3 使用fire實現命令列傳參

2021-10-03 10:30:43 字數 2178 閱讀 6851

在完成原始碼編寫後,有些類或者函式需要通過命令列傳遞引數,可以使用fire工具包:

下面的**中,如果僅需要給add傳遞引數,將add暴露給命令列的方法只需要在檔案末尾新增:fire.fire()

對類中的parse函式,需要暴露給命令的方法為在檔案末尾新增:fire.fire(defaultconfig)

一般不同時暴露上面的兩個。

import fire

class

defaultconfig

(object):

def__init__

(self)

: self.env =

'default'

# visdom environment

self.model =

'alexnet'

# model name must be the same with models in 'models/__init__.py'

self.train_data_root =

'/home/sjtuer/desktop/drl/s6/data/train'

self.test_data_root =

'/home/sjtuer/desktop/drl/s6/data/test'

self.load_model_path =

none

# 'checkpoint/model.py' # load the pre-trained model, if none: no load

self.batch_size =

128 self.use_gpu =

true

self.num_workers =

4# how many workers for loading data

self.print_freq =

20# print info every n batch

self.debug_file =

'/tmp/debug'

# if os.path.exists(debug_file): enter ipdb

self.result_file =

'result.csv'

self.max_epoch =

10 self.lr =

0.001

self.lr_decay =

0.95

# when val_loss increase, lr = lr * lr_decay

weight_decay =1e-

4# loss function

defparse

(self,

**kwargs)

:'''

update configuration based on kwargs dictionary

'''for k,v in kwargs.items():

ifnot

hasattr

(self,k)

: warning.warn(

"warnnin: opt has not attribut %s"

%k)setattr

(self, k, v)

# print(self.__dict__)

# print(self.__class__)

print

('user config:'

)for k, v in self.__dict__.items():

# __class__ 表示當前操作的物件的類

# print(k)

ifnot k.startswith(

'__'):

print

(k,getattr

(self, k)

)opt = defaultconfig(

)def

add(a,b)

:return a+b

if __name__ ==

'__main__'

: dc = defaultconfig(

)print

(dc.batch_size)

dc.parse(

)print

(dc.batch_size)

fire.fire(

)

python3使用 python3使用模組

python內建了很多非常有用的模組,只要安裝完畢,這些模組就可以立刻使用。我們以內建的sys模組為例,編寫乙個hello的模組 usr bin env python3 coding utf 8 a test module author michael liao import sys def tes...

python3實現CryptoJS AES加密演算法

from crypto.cipher import aes from binascii import b2a hex,a2b hex import base64 class aescrypt def init self,key self.key key.encode utf8 self.mode a...

使用python 3實現傳送郵件功能

import smtplib from email.mime.text import mimetext smtpsever smtp.163.com 郵箱伺服器 sender 163.com 郵件位址 password whl3386087 密碼 receivers qq.com 程式設計客棧con...