ImportError: No module named 'pymongo'

2019-02-16 07:33发布

问题:

I have a problem running pymongo on Win 7 (64) with Python 3.4, mongodb 4.2.10. The error output is as follows:

import pymongo
ImportError: No module named 'pymongo'

The code is pretty simple:

import pymongo
from pymongo import MongoClient

client=MongoClient()
db=client.test_db
dict={'A':[1,2,3,4,5,6]}
db.test_collection.insert(dict)
to_print=db.test_collection.find()
print(to_print)

I tried already re-installing Python and MongoDB - did not help. It works when I do it manually in cmd, i.e. mongod.exe and mongo.exe work fine. It appears there is problem with pymongo, but I don't know how to fix it.

回答1:

All you need is to actually install pymongo (currently you just have mongo and python, but they do not know how to speak with each other). This page is telling you exactly what to do:

  • go to pymongo page
  • download and run installer.


回答2:

I am new to Python,

But I think install setuptools is a good idea,

after that:

pip install pymongo


回答3:

Try this:

  1. sudo apt-get install python-pip

  2. sudo pip install pymongo



回答4:

If you have installed pymongo using following command :

sudo pip install pymongo or
sudo -E pip install pymongo 

And still you are getting import error then try to run your python script with sudo like :

sudo python example.py

If you are able to run the script this way, but not without sudo. Then there can be a problem with PYTHON_PATH or Permission issue.

Solving isssue#1 (i.e. PYTHON_PATH) : Location where pip installs packages and location where python looks for packages do not match.

So how do you find where pip install packages ? Run following command :

sudo pip show pymongo

It shows output like this :

---
Name: pymongo
Version: 3.4.0
Location: /usr/local/lib/python2.7/dist-packages

Now you know where pip install packages. Add following line in your .bashrc :

export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages/

Run following command to execute .bashrc again :

source .bashrc

Now try to run python script without sudo. It should run.

If not then do the following :

Solving issue#2 (i.e. Permission): Allow non-root users to read and execute python pacakages.

sudo chmod -R ugo+rX /usr/local/lib/python2.7/

This should solve your all problems. You should be able to run python script without sudo.



回答5:

  1. Make a new folder in your documents like "flask-pymongo"
  2. In your terminal change directory to C:\Users\YOUR_USERNAME\Documents\Flask-PyMongo\
  3. git clone https://github.com/dcrosta/flask-pymongo
  4. cd flask-pymongo
  5. py setup.py develop OR python setup.py develop (depends how python was install to your path)
  6. from anywhere in your terminal use : pip install pymongo

Solution is for windows users