1

Every time that I need to run my python program with:

python my_program.py

I get some error saying that some import was not found.

Some error like this:

Traceback (most recent call last):
  File "graphic.py", line 1, in <module>
    import matplotlib.pyplot as plt
ImportError: No module named 'matplotlib'

Than I run:

sudo python my_program.py

And every thing works just fine. How do I remove the sudo command to run my python codes?

Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50
  • Seems that you install Python under sudo, so the later command without sudo cannot access the folder with root permissions. Try to reinstall python, remember don't always use sudo to install things, you may ruin the permission management. – Menglong Li Oct 08 '17 at 15:37
  • Possible duplicate of [Cannot import a python module that is definitely installed (mechanize)](https://stackoverflow.com/questions/14295680/cannot-import-a-python-module-that-is-definitely-installed-mechanize) – ayrusme Oct 08 '17 at 15:38

2 Answers2

2

ImportError: No module named 'matplotlib' happens when your Python doesn't find the module. sudo changes the enviornment variables; That's why.

To fix this, locate where matplotlib is installed in your computer, and verify the folder is part of your sys.path.

import sys
sys.path
['C:\\Python27\\tests', ..., ...]

Then you've two options: insert that path from your script, i.e adding a line such import sys; sys.path.append(<folder>) or configure PYTHONPATH env variable under your user appending the folder to the path.

PYTHONPATH env variable gets loaded to sys.path on startup.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
1

Best solution to me is a general workflow for all projects: use virtualenviroment]1.

sudo pip3 install virtualenv
virtualenv myenv
source mynenv/bin/activate

Then you should install your libraries again with pip and they will be installed in your virtualenviroment, isolated from everything else.

Alex
  • 1,252
  • 7
  • 21