4

I am trying to install a package with pip. The installation is successful but when trying to import the modules in a subpackage it shows me an error message that says "ModuleNotFoundError: No module named...".

The structure of the package is as follows:

Gestor_Clientes_v2/
   ├─   LICENCE.txt
   ├─   manager_main/
     ├─   __init__.py
     ├─   run.py
     ├─   support.py
     ├─   manager_clients.py
     └─   menu.py
   ├─   README.md
   ├─   setup.py
   └─   test/
     ├─   __init__.py
     └─   test_manager_clients.py

The setup file has the following information:

#!/usr/bin/env python

from setuptools import setup, find_packages

with open('README.md') as file: readme = file.read()

setup(name = 'gestor-clientes',
      version = '2.0',
      author = 'author',
      author_email = 'info@server.com',
      url = 'https://www.server.com/',
      description = 'Un simple gestor de clientes',
      long_description = readme,
      packages = ['manager'],
      test_suite = 'program.test',
      entry_points = {'console_scripts': ['program = manager.run:main']},
      license = 'MIT Licence',
      keywords = 'gestor clientes proyecto',
      classifiers = [
          'Development Status :: 2 - Pre-Alpha',
          'Topic :: Education',
          'Intended Audience :: Education',
          'License :: OSI Approved :: MIT License',
          'Programming Language :: Python :: 3 :: Only',
          'Operating System :: Linux',
          'Operating System :: MacOS',
          'Operating System :: Windows'
      ]



      )

__init__.py

__all__ = ['run', 'manager_clients', 'menu', 'support']

menu.py

"""Fichero principal del programa"""

from sys import path 
path.append('..')

from menu import Menu


def main():
    Menu.options()

if __name__ == '__main__':
    main()

manager_clients.py

""" Administrador de clientes """
import sys
sys.path.append("..")
from manager import support


class ClientData:

    def __init__(self, name: str, first_surname:str, second_surname:str, birth_date:str, nationality:str, nip:str):
        self.name = name
        self.first_surname = first_surname
        self.second_surname = second_surname
        self.birth_date = birth_date
        self.nationality = nationality
        self.nip = nip

    def __str__(self):
        return f"{self.nip}: {self.first_surname} {self.second_surname} {self.name} {self.birth_date} {self.nationality}"

#more code...

menu.py

""" Menú del programa """
from sys import path
path.append('..')

from manager.support import clear_screen
from manager.manager_clients import ClientAdmin

class Menu:

    def options():
        while True:
            clear_screen()  
            print("========================\n",\
                  "|BIENVENIDO AL GESTOR|",\
                  "\n========================",\
                  "\n    Elija una opción    ",\
                  "\n------------------------",\
                  "\n[1] Lista de clientes.",\
                  "\n[2] Buscar cliente.",\
                  "\n[3] Añadir nuevo cliente.",\
                  "\n[4] Actualizar datos del cliente.",\
                  "\n[5] Borrar cliente.",\
                  "\n[6] Salir.")

            option = input(">>> ")
            clear_screen()
            if option == '1':
                print("--INFORMACIÓN DE CLIENTES DISPONIBLES--\n")
                ClientAdmin.info_all_clients()

#more code...

support.py

"""Funciones de ayuda"""
from sys import path
from os import system
import re
from platform import system as OS
path.append("..")

from manager import manager_clients



def clear_screen():
    if OS() == "Windows":
        system('cls')
    else:
        system('clear')


def input_text(min_len, max_len):
    while True:
        text = input("> ")
        if len(text) >= min_len and len(text) <= max_len:
            return text


def is_valid(nip: str):
    if not re.match('[0-9]{2}[A-Z]{3}', nip):
        return False
    for c in manager_clients.ClientAdmin.clients:
        if c.nip == nip:
            return False
    return True

When I run the "run.py" script from the command line the program works correctly just like when I run the tests. When I install the package using pip install Gestor_Clientes_v2/ I get the following:

Processing ./Gestor_Clientes_v2
Building wheels for collected packages: gestor-clientes
  Building wheel for gestor-clientes (setup.py) ... done
  Created wheel for gestor-clientes: filename=gestor_clientes-2.0-cp37-none-any.whl size=6120 sha256=50337e3ed6672cf714d81103c53dd3b957f6c10722c14f952b49baa1a814dbac
  Stored in directory: /tmp/pip-ephem-wheel-cache-be04i_g5/wheels/e4/03/c1/ce19d5766499ca97b57afbdc34598a26f32ca3b9eb01754979
Successfully built gestor-clientes
Installing collected packages: gestor-clientes
Successfully installed gestor-clientes-2.0

The packages appear in pip list as gestor-clientes but when I want to import any of the modules in "manager /" I get the error:

In [1]: import manager                                                
----------------------------------------------------------------------
ModuleNotFoundError                  Traceback (most recent call last)
<ipython-input-1-26cb231bd30e> in <module>
----> 1 import manager

~/anaconda3/lib/python3.7/site-packages/manager/__init__.py in <module>
----> 1 from manager import run
      2 from manager import manager_clients
      3 from manager import menu
      4 from manager import support

~/anaconda3/lib/python3.7/site-packages/manager/run.py in <module>
      4 path.append('..')
      5 
----> 6 from menu import Menu
      7 
      8 

ModuleNotFoundError: No module named 'menu'

In [2]:

I have been guided by different examples of packages with a similar structure and when I install them I can import their modules.

I am relatively new to Python and there are still many things that I don't know well and I think there is something missing in my modules and my setup file.

I hope you can help me review the structure of my package and give me some ideas to solve my problem. Thanks in advance.

Rodrigo López
  • 403
  • 1
  • 4
  • 17
  • make sure you don't have 2 python instances in your environment. you can verify that you do have this module with just running the python interpreter and trying to import it without the running of all program. you can also make sure your model name is right – Oded BD Feb 17 '20 at 05:16
  • I'm not an expert but I kind of think that python is looking in your site-packages for a module called 'manager' and that's not the package name that python can find. Try opening a python shell and typing`from gestor-clientes import manager`, or `import gestor-clientes` and see what happens. If it doesn't throw an error on one of those, that's the issue. – Michael Green Feb 17 '20 at 05:24
  • @OdedBD I currently have Anaconda installed on my system. I have Windows and Linux xfce and on both systems I have the same problem. – Rodrigo López Feb 17 '20 at 05:52
  • @MichaelGreen Previously, I had the "manager" and "test" directories within another directory that I call "program" and right there also put a __init__.py file that, as I understand it, allows Python to consider it as a package but the problem is same too. – Rodrigo López Feb 17 '20 at 05:55
  • 1
    @RodrigoLópez Is this problem still occurring? I have came across a similar situation and I solved it with the great answer on this post: [pip install . creates only the dist-info not the package](https://stackoverflow.com/questions/50585246/pip-install-creates-only-the-dist-info-not-the-package) Do you need further help ? – eidal May 25 '22 at 09:38

1 Answers1

1

I think you should try to install the package using pip3, based on the previous syntax

pip3 install packagename

In some cases, when you have a preinstalled Python 2, this can be the solution, because even though you’ve installed the package, it can only be accessed by the Python 2 interpreter as they are different installations.