简体   繁体   中英

Install dependencies from setup.py

I wonder if as well as.deb packages for example, it is possible in my setup.py I configure the dependencies for my package, and run:

$ sudo python setup.py install

They are installed automatically. Already researched the internet but all I found out just leaving me confused, things like "requires", "install_requires" and "requirements.txt"

Just create requirements.txt in your lib folder and add all dependencies like this:

gunicorn
docutils>=0.3
lxml==0.5a7

Then create a setup.py script and read the requirements.txt in:

import os
lib_folder = os.path.dirname(os.path.realpath(__file__))
requirement_path = lib_folder + '/requirements.txt'
install_requires = [] # Here we'll get: ["gunicorn", "docutils>=0.3", "lxml==0.5a7"]
if os.path.isfile(requirement_path):
    with open(requirement_path) as f:
        install_requires = f.read().splitlines()
setup(name="mypackage", install_requires=install_requires, [...])

The execution of python setup.py install will install your package and all dependencies. Like @jwodder said it is not mandatory to create a requirements.txt file, you can just set install_requires directly in the setup.py script. But writing a requirements.txt file is a best practice.

In the setup function call, you also have to set version , packages , author , etc, read the doc for a complete example: https://docs.python.org/3/distutils/setupscript.html

You package dir will look like this:

├── mypackage
│   ├── mypackage
│   │   ├── __init__.py
│   │   └── mymodule.py
│   ├── requirements.txt
│   └── setup.py

Another possible solution

try:
    # for pip >= 10
    from pip._internal.req import parse_requirements
except ImportError:
    # for pip <= 9.0.3
    from pip.req import parse_requirements

def load_requirements(fname):
    reqs = parse_requirements(fname, session="test")
    return [str(ir.req) for ir in reqs]

setup(name="yourpackage", install_requires=load_requirements("requirements.txt"))

You generate egg information from your setup.py , then you use the requirements.txt from these egg information:

$ python setup.py egg_info
$ pip install -r <your_package_name>.egg-info/requires.txt 

In Python 3.4+, it is possible to use the Path class from pathlib , to do effectively the same thing as @hayj answer.

from pathlib import Path
import setuptools

...

def get_install_requires() -> List[str]:
    """Returns requirements.txt parsed to a list"""
    fname = Path(__file__).parent / 'requirements.txt'
    targets = []
    if fname.exists():
        with open(fname, 'r') as f:
            targets = f.read().splitlines()
    return targets

...

setuptools.setup(
    ...
    install_requires=get_install_requires(),
    ...
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM