0

I need to install a package, matplotlib. Install it within the code. I am a beginner and have very little knowledge about python coding.

import subprocess
import sys

def install(matplotlib):
    subprocess.call([sys.executable, "-m", "pip", "install", matplotlib])

Does that means. after the computer finish the code above, I can start using matplotlib commands?

But it don't seem like that, I stil get an error when:

import matplotlib.pyplot as plt

The error:

No module named 'matplotlib'

How I can fix this? I know this is a very basic problem, but I need help. Any help is appreciated!

2 Answers 2

2

You could use pip's python module to achieve that.

import pip

def install(package):
    if hasattr(pip, 'main'):
        pip.main(['install', package])
    else:
        pip._internal.main(['install', package])
Sign up to request clarification or add additional context in comments.

11 Comments

Yes - that, and safeguards for when things go wrong, and better yet - a check for matplotlib already being installed is the way to go.
Getting #AttributeError: module 'pip' has no attribute 'main'
AttributeError: module 'pip' has no attribute '_internal'
@DeveshKumarSingh What pip version are you using?
$ pip3.7 -V pip 19.0.3 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)
|
1

Try using the pip library:

UPDATED

import pip
from pip import main
from pip._internal import main 

if hasattr(pip, 'main'):
    pip.main(['install', 'matplotlib'])
else:
    pip._internal.main(['install', 'matplotlib'])

2 Comments

module 'pip' has no attribute 'main'
@Zing I have updated my answer :D I have this working in Python 3.7 :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.