[問題] 如何把Python scripts包成可散佈的CLI?

看板Python作者 (missing)時間6年前 (2018/06/16 12:19), 編輯推噓1(105)
留言6則, 2人參與, 6年前最新討論串1/3 (看更多)
假設我有一檔案recognize.py如下: ```python import argparse import json from multiprocessing import Pool from ocr_tools import Organize organizer = Organize() parser = argparse.ArgumentParser(description="Recognize the contents on a lab report and return a json string.") parser.add_argument("-i", "--image", nargs="*", required=True, help="path to input image file") args = parser.parse_args() if __name__ == "__main__": with Pool() as p: report_set = json.dumps({"report_set": p.map(organizer.finalize_report, args.image)}, ensure_ascii=False) print(report_set) ``` 其中,`ocr_tools`是一個我自己寫的大型模組,我已經幫它準備了requirements.txt: numpy==1.14.3 regex==2018.2.21 requests==2.18.4 pandas==0.23.0 opencv_python==3.4.1.15 scikit_learn==0.19.1 所以,使用者如果拿到我的程式碼並安裝好所需套件, 他就可以運行`python recognize.py -i <path_to_image>`。 而我好奇的是:有沒有可能更進一步,讓使用者只要透過某些步驟(安裝?), 完成之後,他就可以做到例如:`ocr -i <path_to_image>`? 概念上就像git或是homebrew,使用者甚至不需要知道它們是用什麼語言寫的。 我在網路上有找到一篇教學: How Do I Make My Own Command-Line Commands Using Python? https://dbader.org/blog/how-to-make-command-line-commands-with-python 但是他這裡面的方法只在本地有效,沒有提到要怎麼散佈。 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.121.6.93 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1529122780.A.971.html

06/16 17:58, 6年前 , 1F
在 setup.py 內用 entry_points 內透過 console_script
06/16 17:58, 1F

06/16 17:59, 6年前 , 2F
指定程式進入點,用 python setup.py 安裝之後
06/16 17:59, 2F

06/16 17:59, 6年前 , 3F
系統會自動在 /usr/local/bin 等這類路徑產生 script
06/16 17:59, 3F

06/16 18:00, 6年前 , 4F
unix 系統一般 PATH 都會搜尋該目錄,所以可以找到執行
06/16 18:00, 4F

06/16 18:01, 6年前 , 5F
比方可以參考: https://goo.gl/1QH6nj
06/16 18:01, 5F

06/17 21:41, 6年前 , 6F
謝謝!我再研究看看~
06/17 21:41, 6F
文章代碼(AID): #1R98_Sbn (Python)
文章代碼(AID): #1R98_Sbn (Python)