» Make grep CLI App in Python » 2. Development » 2.7 Add setup.py

Add setup.py

The setup.py file in a Python project is commonly used to define the metadata and configuration for distributing and packaging the project. It is used with the setuptools library to provide information about the project such as its name, version, author, dependencies, and other details necessary for packaging and distribution.

setup.py:

from setuptools import setup, find_packages

setup(
    name='lr-grepy',
    version='0.1.0',
    packages=find_packages(),
    install_requires=[
        # List your project dependencies here
    ],
    entry_points={
        'console_scripts': [
            'grepy=grepy_cli:main',
        ],
    },
    author='Literank',
    license='MIT',
    description='An example project\'s grep-like CLI app implemented in Python.',
    url='https://github.com/Literank/lr_grepy',
)

After setting up setup.py, you can use it to perform various tasks, such as installing the project locally, creating distribution packages, and uploading them to the Python Package Index (PyPI).

To install the project locally, run the following command in the terminal:

pip install . # Or pip3 install .

This will install your project along with its dependencies.

Try to run your command:

grepy

It says:

Traceback (most recent call last):
  File "/usr/local/bin/grepy", line 5, in <module>
    from grepy_cli import main
ModuleNotFoundError: No module named 'grepy_cli'

It's a ModuleNotFoundError triggered by the complicated module mechanism.

You can overcome this by moving grepy_cli.py to grepy/cli.py, then the new folder structure would be:

.
├── LICENSE
├── README.md
├── grepy
│   ├── __init__.py
│   ├── cli.py
│   └── grep.py
├── requirements.txt
├── setup.py
└── tests
    └── test_grep.py

Update your setup.py:

entry_points={
    'console_scripts': [
        'grepy=grepy.cli:main', # grepy_cli => grepy.cli
    ],
},

Install and try again.

pip3 install .
grepy -n result grepy/cli.py

You should see something similar to this:

35: result = grep_recursive(args.pattern,
38: result = grep(args.pattern, args.file_path, get_options(args))
41: print(grep_count(result))
43: print_result(result, args.line_number)
55: def print_result(result: Dict[str, MatchResults], line_number_option: bool):
57: file_count = len(result)
58: for file_path, lines in result.items():

Congratulations🎉! So far so good!

If you want to install your project locally but still be able to edit the code and see the changes reflected without reinstalling, you can use the -e flag with pip. This installs your project in "editable" mode, creating a symlink to the source code rather than copying it.

# -e stands for "editable"
pip install -e .

Note: In editable mode, please make sure your python site-packages directory is in your system PATH.

PrevNext