pip install -e successful, import fails: ModuleNot

2019-08-04 17:56发布

问题:

I'm trying to install a module I'm developing. When I use 'pip install -e .', it outputs 'Successfully installed gym-mabifish' but when I try to import the module using 'import gym_mabifish' I'm getting 'ModuleNotFoundError: No module named "gym_mabifish"'.

Here's the structure of the package:

gym-mabifish/
     setup.py ( https://pastebin.com/1wNykyKw )
     gym_mabifish/
          __init__.py ( https://pastebin.com/GtQid3Nk )
          envs/
               __init__.py ( https://pastebin.com/Txfk0ezE )
               mabifish_env.py ( https://pastebin.com/g50zBbus )

I'm using the random_agent from OpenAI gym to test it. ( https://pastebin.com/72LETtxd )

The package is shown in pip list:

gym-mabifish (0.0.1, x:\path\to\project\gym-mabifish)

回答1:

Most likely, you have two (or more) Python installations, and your pip and python come from different installations.

Ideally, you want to solve that problem. But in some cases, it's very difficult. On Windows, managing the PATH can be a nightmare. On macOS, if you install a second Python 2.7 alongside the Apple pre-installed Python 2.7 (which doesn't come with pip), things get confusing.

So, the officially recommended solution nowadays is to just use the -m flag to run pip using whichever command you normally use to run Python.

Everything below is as of early 2018. It's changed a few times in the past few years, and may well change again in the future, so it's always best to go right to Installing Python Modules in the docs, or the Python Packaging User Guide. But as a summary:

Ideally you're using a virtual environment, in which case this is just python. But if not:

  • Windows:
    • py
  • *nix:
    • python only if you're explicitly using whatever came with your OS/distro as a default.
    • python3 if you're using 3.x on *nix](https://www.python.org/dev/peps/pep-0394/)
    • python2.7 if you're using Apple's default Python 2.7 on macOS.
    • python2 if you're using any other 2.x on *nix.

So, for example, on Windows, it should be:

py -m pip install gym-mabifish

… and then when you run your script like this:

py myscript.py

… it will be able to import gym_mabifish.