Search code examples
pythonsetuptools

ImportError when using console_scripts in setuptools


I am trying to build a program called dnsrep in Python, I am using setuptools so that I can call the dnsrep module without using the command python dnsrep. The setup.py script I wrote is given below:

from setuptools import setup, find_packages

setup(
    name='dnsrep',
    version='0.1',
    description='Program that gives a reputation score to url\'s\n.',
    entry_points = {
        'console_scripts': ['dnsrep = dnsrep:main']
    },
    zip_safe=True,
)

I install the module by using the command:

python setup.py install

My module gets registered but when I run it I get the error:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/bin/dnsrep", line 9, in <module>
    load_entry_point('dnsrep==0.1', 'console_scripts', 'dnsrep')()
  File "build/bdist.macosx-10.6-intel/egg/pkg_resources/__init__.py", line 521, in load_entry_point
  File "build/bdist.macosx-10.6-intel/egg/pkg_resources/__init__.py", line 2632, in load_entry_point
  File "build/bdist.macosx-10.6-intel/egg/pkg_resources/__init__.py", line 2312, in load
  File "build/bdist.macosx-10.6-intel/egg/pkg_resources/__init__.py", line 2318, in resolve
ImportError: No module named dnsrep

Solution

  • You have to install your python script, before you can call it via your defined entry point

    This is my dummy project:

    dnsrep/
    ├── dnsrep.py
    └── setup.py
    

    This is how setup.py looks like:

    from setuptools import setup
    setup(
        name='dnsrep',
        version='0.1',
        description='Program that gives a reputation score to url\'s\n.',
        py_modules=['dnsrep'],
        entry_points = {
            'console_scripts': ['dnsrep = dnsrep:main']
        },
        zip_safe=True,
    )
    

    Note the argument py_modules=['dnsrep'], which installs dnsrep.py as a new module.

    Finally, this is my dummy implementation of dnsrep.py:

    from __future__ import print_function
    
    def main():
        print("Hey, it works!")
    

    After installing, everything works as expected and $ dnsrep prints: Hey, it works!