Creating and uploading a Python package to PyPi (Python Package Index) is an essential skill for sharing your work with the community. In this blog post, we’ll walk through the complete process using an example package, file_compressor, which compresses files into a .zip
format. By the end of this guide, you’ll be able to create, build, and upload your own Python package to PyPi.
Let’s get started!
Step 1: Setting Up Your Environment
Before we begin creating the Python package, you need to set up your environment with the necessary tools. If you don't have Python installed, please install it from python.org.
We will also need a few packages to help build and upload the package:
pip install setuptools wheel twine
What Are These Packages?
- setuptools: A tool for packaging Python projects.
- wheel: A packaging format for Python distribution.
- twine: A tool to securely upload your package to PyPi.
Step 2: Create Your Package Directory
Now that you have the necessary tools, create a directory for your project. Inside this directory, you will organize your Python package and related files.
Here’s how your directory structure might look for the file_compressor package:
file_compressor/
├── file_compressor/ # Package directory containing the Python code
│ └── __init__.py # Mark this directory as a Python package
├── setup.py # Metadata about the package
├── LICENSE # License information (MIT, GPL, etc.)
├── README.md # Documentation about your package
├── MANIFEST.in # Include additional non-Python files (optional)
└── tests/ # Unit tests for the package
Package Code Example:
In the file_compressor/
directory, you might create a Python file, such as compress.py
, which contains the core functionality of your package, like compressing files into a .zip
format.
Here’s an example implementation of compress.py
:
import zipfile
import os
def compress_file(input_file, output_file):
"""Compress a single file into a zip archive."""
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipf.write(input_file, os.path.basename(input_file))
print(f"File {input_file} compressed to {output_file}.")
Step 3: Create the setup.py
File
The setup.py
file contains important metadata for your Python package, such as its name, version, and description. Here is an example setup.py
for file_compressor:
from setuptools import setup, find_packages
setup(
name='file_compressor', # Name of your package
version='0.1.0', # Initial version
packages=find_packages(), # Find all Python packages
description='A Python package for compressing files into .zip format',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Your Name',
author_email='your-email@example.com',
url='https://github.com/your-username/file_compressor', # Link to GitHub repository
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
install_requires=[], # Add any dependencies here (if needed)
python_requires='>=3.6', # Specify the minimum Python version
)
-
name: The name of your package (e.g.,
file_compressor
). -
version: The current version of your package (start with
0.1.0
for the first release). - description: A short description of what your package does.
-
long_description: A detailed description (this can be fetched from your
README.md
file). - author: Your name or organization.
- author_email: Your email address.
- url: The URL to your package's homepage (usually your GitHub repository).
Step 4: Create a README.md
A README.md
file is essential to explain the purpose of your package and how to use it. Here's a simple example:
# File Compressor
A Python package that compresses files into `.zip` format.
## Installation
bash
pip install file-compressor
## Usage
python
from file_compressor import compress_file
compress_file('path/to/your/file.txt', 'path/to/output/file.zip')
Step 5: Build the Package
Now it’s time to build the package. In your project directory (where setup.py
is located), run the following commands:
python setup.py sdist bdist_wheel
This command creates distribution archives, which include:
-
sdist
: The source distribution, a.tar.gz
file. -
bdist_wheel
: The wheel distribution, a.whl
file.
These files will be stored in a dist/
directory inside your project folder.
Step 6: Create a PyPi API Token
To securely upload your package to PyPi, you need to create an API token. Here’s how:
- Log in to PyPi: Go to https://pypi.org/ and log in.
- Go to Account Settings: Click your username in the top-right corner and select "Account settings".
-
Create an API Token:
- Scroll down to the API tokens section.
- Click "Add API token".
- Provide a name for the token (e.g., "file_compressor upload").
- Click "Add token".
- Save the API token: Make sure to copy and securely store the token. You’ll only see it once.
Step 7: Upload to PyPi
Once the package is built, you can upload it using twine
. Run the following command to upload the distribution files to PyPi:
twine upload dist/* -u __token__ -p <your-pypi-api-token>
Replace <your-pypi-api-token>
with the actual token you generated in the previous step.
This will securely upload your package to PyPi. If the upload is successful, you'll see a confirmation message.
Step 8: Verify Your Package on PyPi
After uploading, visit https://pypi.org/project/file-compressor/ to verify that your package is live on PyPi. You should see the version, description, and files listed.
Step 9: Install and Test Your Package
To ensure your package is working correctly, try installing it in a new Python environment:
pip install file-compressor
Once installed, test it in a Python script:
from file_compressor import compress_file
compress_file('path/to/your/file.txt', 'path/to/output/file.zip')
If the package works as expected, congratulations! Your package is ready for others to use.
Step 10: Updating Your Package
In the future, if you make any updates to your package, follow these steps:
- Modify your package (e.g., add new features or fix bugs).
- Update the version number in
setup.py
(e.g., from0.1.0
to0.2.0
). - Repeat the build and upload steps to publish the new version.
Conclusion
In this guide, we've gone over the complete process of creating a Python package, specifically the file_compressor package, from scratch. You learned how to:
- Set up the package structure.
- Write the
setup.py
andREADME.md
files. - Build and upload your package to PyPi.
- Use an API token for secure uploads.
With this knowledge, you can now share your Python packages with the world via PyPi! If you want to explore more about package creation, check out the official PyPi documentation.
Top comments (0)