Home > Blockchain >  Automatically install Python module when code is ran
Automatically install Python module when code is ran

Time:01-26

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

CodePudding user response:

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!

CodePudding user response:

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"])
  • Related