Install module to site-packages with setuptools

2019-08-17 09:03发布

问题:

I'm trying to upload a CLI to PIP that, once installed, will run when the user types myscript

My folder structure is like this:

lib
  myscript
    __init__.py (empty)
    __main__.py (code that needs to run)
    utilities.py (needs to be imported from main)

scripts
  myscript

setup.py

My setup.py should install the lib.myscript package and install myscript as a command-line module

setup.py

import setuptools
setuptools.setup(
    name='myscript',
    version='1.0',
    scripts=['./scripts/myscript'],
    packages=['lib.myscript'],
    install_requires=['setuptools', 'pandas >= 0.22.0', 'numpy >= 1.16.0'],
    python_requires='>=3.5'
)

scripts/myscript

#!/usr/bin/env bash

if [[ ! $@ ]]; then
    python -m myscript -h
else
    python -m myscript $@
fi

Once I do python setup.py install, myscript is installed as a command-line module and it runs. However, it throws an error saying that there is no module named myscript.

回答1:

You haven't install myscript, you've installed lib.myscript so try this: python -m lib.myscript. And for Python to recognize lib as a package create an empty file lib/__init__.py.

PS. This code:

#!/usr/bin/env bash

if [[ ! $@ ]]; then
    python -m myscript -h
else
    python -m myscript $@
fi

could be simplified as:

#!/usr/bin/env bash
exec python -m myscript ${@:--h}

which in shell-speak means "Use $@ if not empty, else -h"