Python新手求助:如何将非PyPi包安装至虚拟环境并维护版本
Hey there! Let's break this down step by step since you're new to Python—no worries, we've all fumbled with package management at first 😊
You don't have to mess with manual path hacks for GitHub packages! Pip can install directly from Git repositories, and you can even pin specific versions to keep things stable:
- Install the latest version from the main branch:
pip install git+https://github.com/[username]/[repo-name].git - Pin to a specific release tag (great for version control):
pip install git+https://github.com/[username]/[repo-name].git@v1.2.3 - To save this to your
requirements.txtso others (or future you) can replicate the environment, add this line:
Thegit+https://github.com/[username]/[repo-name].git@v1.2.3#egg=[package-name]#egg=part tells pip what to name the package inpip listoutput.
lib Library (With Versioning) Manual path additions work for quick tests, but if you want proper version management, turning your lib into an installable package is the way to go—it's easier than it sounds!
Step 1: Structure your lib like a standard Python package
Rearrange your project like this (you only need to add a couple files):
your-project/ ├── venv/ ├── main.py └── lib/ ├── pyproject.toml # Modern config file (optional but recommended) ├── setup.py # Legacy but widely supported └── your_lib/ # Your actual code goes here ├── __init__.py └── any_modules.py
Step 2: Add version info to your setup file
In setup.py, define your package's name and version (update this whenever you make breaking changes):
from setuptools import setup, find_packages setup( name="my-custom-lib", version="0.1.0", packages=find_packages(), # Automatically finds your code in `your_lib/` )
Step 3: Install it in editable mode
Run this in your virtual environment:
pip install -e ./lib
The -e flag means "editable"—any changes you make to your lib code will take effect immediately without reinstalling. Now when you run pip list, you'll see my-custom-lib with its version number listed!
If you really don't want to restructure (temporary fix)
For quick tests, you can add the lib path to Python's sys.path in your main script, but note this doesn't track versions:
import sys from pathlib import Path # Add the lib directory to Python's module search path sys.path.append(str(Path(__file__).parent / "lib")) # Now you can import modules from lib import my_custom_module
- For GitHub packages: Check the repo's Releases page periodically for new versions. When you want to update, just change the tag in your
requirements.txtand runpip install -r requirements.txt --upgrade. - For your custom
lib: Every time you push a significant update, bump the version number insetup.py. If you're using Git for your project, you can tag these versions withgit tag v0.2.0to make it easy to track when changes were made.
内容的提问来源于stack exchange,提问作者Barka

