How can I 'embed' a Python library in my own Python package?
Take the Requests library, for instance. How could I integrate it into my own package, the objective being to allow me to run my application on different machines without actually installing Requests on every one, but having it in the same folder as my package?
Is this even possible?
If it's a pure python library (no compiled modules) you can simply place the library in a folder in your project and add that folder to your module search path. Here's an example project: |- application.py |- lib | `- ...
Creating PackagesWhenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers Python. Create a directory and include a __init__.py file in it to tell Python that the current directory is a package.
If it's a pure python library (no compiled modules) you can simply place the library in a folder in your project and add that folder to your module search path. Here's an example project:
|- application.py |- lib | `- ... |- docs | `- ... `- vendor |- requests | |- __init__.py | `- ... `- other libraries...
The vendor
folder in this example contains all third party modules. The file application.py
would contain this:
import os import sys # Add vendor directory to module search path parent_dir = os.path.abspath(os.path.dirname(__file__)) vendor_dir = os.path.join(parent_dir, 'vendor') sys.path.append(vendor_dir) # Now you can import any library located in the "vendor" folder! import requests
As noted by seeafish in the comments, you can install packages directly into the vendor directory:
pip install <pkg_name> -t /path/to/vendor_dir
If you only need to run your application may be pyinstaller packaging is a better option.
It will create a single bundle with everything that is needed, including Python, to avoid dependencies on the system you're running in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With