skip to Main Content

I am currently finishing a school project making a game of Blackjack. I was using Replit to code and everything was fine. I recently tried to run it at home on Visual Studio Code but it said a module named "matplotlyb.pyplot" wasn’t installed. I seem to understand now that you have to install it manually. When my project is done, it will be sent to an external examiner who will review it. Is there anyway to automatically download the module when the code is ran so the examiner won’t have to?

Here’s what I’m looking for:

import matplotlib.pyplot as plt

#something that installs it if not already installed

2

Answers


  1. Best practice would be to include a requirements.txt file along with your project. The file should contain all the required packages in the format

    packagename==version

    You could also use the below to generate the requriements.txt

    pip freeze > requirements.txt
    

    pip freeze gives you the list of all installed Python modules along with the versions

    To run your install all the dependencies, you could just use:

    pip install -r requirements.txt
    

    Hope this helps!

    Login or Signup to reply.
  2. Simply wrap things in a try.. except and don’t forget to use sys.executable to ensure that you will call the same pip associated with the current runtime.

    import subprocess
    import sys
    
    # lazy import + install
    try:
        import matplotlib.pyplot as plt
    except ModuleNotFoundError:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "matplotlib"])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search