亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何設計一個接受 Python 函數或代碼的命令行界面 (CLI)?

如何設計一個接受 Python 函數或代碼的命令行界面 (CLI)?

慕碼人8056858 2021-09-28 21:12:01
我有一個函數可以解析具有特定規則的給定字符串。我想為此功能設計一個 CLI 界面。但問題是我希望用戶應該能夠使用它自己的 READER & WRITER 函數通過 CLI 調用這個函數。為了清楚起見,這里有一個示例代碼和我要解釋的內容的演示。# mylib.py# piece of code that belongs to my libdef parser(_id, text):    # parse the text & do some magic    return (_id, parsed_text)# user-side codedef reader():   # read from a database   # or file or network or who knows where   yield (_id, text)# user-side codedef writer(_id, text):   # write to somewhere   return True # or false depends on write action示例調用應該是這樣的:$ python mylib.py --reader <something-that-I-dont-know>我不想使用eval技巧,但我也希望用戶在將數據傳遞到我的庫時應該靈活。這可能嗎?或者我應該嘗試另一種方法?
查看完整描述

1 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

在@AlexHall 的幫助下,我想出了以下解決方案:


import pathlib

import importlib.util



def load_module(filepath):

    module_path = pathlib.Path(filepath)

    abs_path = module_path.resolve()

    module_name = module_path.stem


    spec = importlib.util.spec_from_file_location(module_name, abs_path)

    module = importlib.util.module_from_spec(spec)

    spec.loader.exec_module(module)

    return module

使用此功能,即使模塊不在路徑中,我也可以導入文件系統中存在的任何有效 python 模塊。


這是一個示例用法:


parser = make_parser(prog="tokenizer")

args = parser.parse_args()

module = load_module(args.writer) # if nothing is passed, default action defined in the parser

writer = module.writer

module = load_module(args.reader)

reader = module.reader

# do what you want to do with them


查看完整回答
反對 回復 2021-09-28
  • 1 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號