Skip to content Skip to sidebar Skip to footer

Created A Pypi Package And It Installs, But When Run It Returns An Import Error

I've created a simple package and was able to publish it in PyPI. It's file struc is: DaysGrounded\ DaysGrounded\setup.py DaysGrounded\setup.cfg DaysGrounded\requirements.txt DaysG

Solution 1:

This is due to the difference between the three ways of invoking a python package:

  1. python daysgrounded
  2. python daysgrounded/__main__.py
  3. python -m daysgrounded

If you try each of these on your project you'll notice that the third method doesn't work, which is exactly the one runpy uses. The reason it doesn't work is because your sys.path is incorrect, because python adds daysgrounded/ to your sys.path for the first two ways, but not the third.

In order for all three ways to work, you have to make sure that your sys.path is correct, and there are two ways of doing this.

If you want to be able to do import cli, sys.path should be daysgrounded/, which means you need to modify __init__.py to add it to sys.path:

import sys
import os.path
sys.path.insert(1, os.path.dirname(__file__))

If you want to be able to do from daysgrounded import cli, sys.path should be the directory above daysgrounded/, which means you need to modify __main__.py to add it to sys.path:

import sys
import os.path
sys.path.insert(1, os.path.dirname(sys.path[0]))

Post a Comment for "Created A Pypi Package And It Installs, But When Run It Returns An Import Error"