搜尋
首頁後端開發Python教學在 GitHub 上建立並發布私有 Python 套件

介紹

身為軟體工程師,我們經常發現自己在不同的模組和專案中重複使用程式碼。但讓我們面對現實吧,這種重複帶來了一個挑戰:當我們需要調整或修復程式碼時,我們必須在多個地方進行相同的更改。對於我們這些重視效率和自動化的人來說,解決方案很明確 - 創建一個可以在我們的專案中安裝和使用的單獨包。
然而,在處理機密程式碼時,我們不能簡單地將套件發佈到像 PyPI 這樣的公共儲存庫上。相反,我們需要將其部署到私人儲存庫,例如 GitHub 或 GitLab。這種方法使我們能夠保持安全性,同時仍然受益於可重複使用套件的便利性。

在本教學中,我們將引導您完成以下過程:

  1. 建立 Python 套件
  2. 將套件部署到私人儲存庫 (GitHub)
  3. 在虛擬環境(venv)中安裝軟體包

透過執行這些步驟,您將能夠減少程式碼重複並簡化專案中共享程式碼的維護。

注意:DRY 不僅僅代表「Don’t Repeat Yourself」——它也是一種生活方式的選擇。

Create and Release a Private Python Package on GitHub

1. 設定項目結構

首先,讓我們為 Python 套件設定一個基本的專案結構:

my-package/
├── my_package/
│   ├── __init__.py
│   └── module1.py
├── setup.py
├── build.pipeline.yml
├── requirements.txt
├── .gitignore
├── README.md
├── MANIFEST.in
└── LICENSE

讓我們來剖析一下我們的私有 Python 套件。每個檔案和目錄在使我們的套件正常運作和可安裝方面發揮著至關重要的作用:

  • my-package/:這是我們專案的根目錄。它就像一座房子,裡麵包含我們需要的所有房間(文件)。
  • my_package/:此子目錄是實際 Python 程式碼所在的位置。為了清楚起見,它的名稱與我們的套件相同。
    • __init__.py:此檔案使 Python 將目錄視為套件。它可以為空,也可以執行套件的初始化程式碼。
    • module1.py:這是我們放置主要程式碼的地方。根據套件的複雜程度,您可以擁有多個模組檔案。
  • setup.py:將此視為我們包的說明手冊。它包含有關我們的套件的元資料(如其名稱和版本)並列出其依賴項。該檔案對於使我們的套件可透過 pip 安裝至關重要。
  • requirements.txt:該檔案列出了我們的專案所依賴的所有外部Python套件。它就像 pip 的購物清單,準確地告訴它要安裝什麼才能使我們的包正常工作。
  • README.md:這是我們專案的歡迎墊。它通常是人們訪問我們的 GitHub 儲存庫時看到的第一件事,因此我們用它來解釋我們的套件的用途、如何安裝以及如何使用它。
  • .gitignore:該檔案告訴 Git 要忽略哪些檔案或目錄。它可以方便地將編譯的程式碼、臨時檔案或敏感資訊保持在版本控制之外。
  • 許可證:此文件指定其他人如何使用、修改或分發我們的套件。這對於開源專案至關重要,有助於保護我們的工作。
  • MANIFEST.in:此檔案用於在我們的套件分發中包含非 Python 檔案。如果我們有需要包含的資料檔案、文件或其他資源,我們會在此處列出。
  • build.pipeline.yml:此檔案定義我們的持續整合/持續部署(CI/CD)管道。當我們將變更推送到 GitHub 儲存庫時,它會自動執行執行測試和建置套件等任務。

2. 建立包代碼

讓我們在套件中建立一個簡單的模組。在 my_package/module1.py 中:

my-package/
├── my_package/
│   ├── __init__.py
│   └── module1.py
├── setup.py
├── build.pipeline.yml
├── requirements.txt
├── .gitignore
├── README.md
├── MANIFEST.in
└── LICENSE

在 my_package/__init__.py 中,我們將導入我們的模組:

class Hello:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}!"

3.建立setup.py

setup.py 檔案對於打包我們的專案至關重要。這是一個基本範例:

from .module1 import Hello

4.建立requirements.txt

在我們的requirements.txt 檔案中,我們包含了建置和分發套件所需的依賴項:

from setuptools import setup, find_packages

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

setup(
    name="my_package",
    version="0.1",
    include_package_data=True,
    python_requires='>=3.8',
    packages=find_packages(),
    setup_requires=['setuptools-git-versioning'],
    install_requires=requirements,
    author="Abdellah HALLOU",
    author_email="abdeallahhallou33@gmail.com",
    description="A short description of your package",
    long_description=open('README.md').read(),
    long_description_content_type="text/markdown",
    classifiers=[
        "Programming Language :: Python :: 3.8",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    version_config={
       "dirty_template": "{tag}",
    }
)

5. 建置和安裝你的包

安裝要求。為了簡單起見,我們將使用 Python 虛擬環境。

setuptools==69.2.0
wheel
twine

建造我們的包:

python -m venv env
source env/bin/activate # for linux and mac
./env/Scripts/activate # for windows
pip install -r requirements.txt

要在本地安裝我們的軟體包以進行測試:

python setup.py sdist bdist_wheel

您可以使用 .gitignore 檔案提交您的工作並忽略資料夾:

https://github.com/github/gitignore/blob/main/Python.gitignore

6. 使用標籤在 GitHub 上發布套件

要發佈包,請先在專案 my-package/ 的根目錄下建立一個 build.pipeline.yml 檔案並提交。部署將使用 twine 完成,這是我們之前安裝的函式庫:

my-package/
├── my_package/
│   ├── __init__.py
│   └── module1.py
├── setup.py
├── build.pipeline.yml
├── requirements.txt
├── .gitignore
├── README.md
├── MANIFEST.in
└── LICENSE

如果您需要在模組安裝中包含非 Python 文件,可以使用 MANIFEST.in 檔案。此文件指定您的軟體包分發中應包含哪些附加文件。

class Hello:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}!"

然後上傳套件:

from .module1 import Hello

7. 安裝軟體包

建立存取權杖:

  • 前往設定>;開發者設定> 個人存取令牌(經典) > 產生新令牌
  • 確保檢查 write:packages 範圍以授予必要的權限。

獲得令牌後,請確保其安全,因為您將需要它來安裝軟體包。

在您的電腦上,您可以使用以下範本安裝您的私有套件:

from setuptools import setup, find_packages

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

setup(
    name="my_package",
    version="0.1",
    include_package_data=True,
    python_requires='>=3.8',
    packages=find_packages(),
    setup_requires=['setuptools-git-versioning'],
    install_requires=requirements,
    author="Abdellah HALLOU",
    author_email="abdeallahhallou33@gmail.com",
    description="A short description of your package",
    long_description=open('README.md').read(),
    long_description_content_type="text/markdown",
    classifiers=[
        "Programming Language :: Python :: 3.8",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    version_config={
       "dirty_template": "{tag}",
    }
)

結論

幹得好,你現在知道如何在 GitHub 上使用 Python 建立和部署自己的私有套件了。

Github 儲存庫連結:https://github.com/ABDELLAH-Hallou/Private-Python-Package-Deployment

以上是在 GitHub 上建立並發布私有 Python 套件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?列表和陣列之間的選擇如何影響涉及大型數據集的Python應用程序的整體性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

說明如何將內存分配給Python中的列表與數組。說明如何將內存分配給Python中的列表與數組。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python數組中指定元素的數據類型?您如何在Python數組中指定元素的數據類型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什麼是Numpy,為什麼對於Python中的數值計算很重要?什麼是Numpy,為什麼對於Python中的數值計算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

討論'連續內存分配”的概念及其對數組的重要性。討論'連續內存分配”的概念及其對數組的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版