0

Is there any cute way for a python script to tell that it's missing python packages, and then import those? I could only think of some yucky approach like this. Basically you would read in the python file, check what modules were imported, then use pip list to check if those really existed or not. If they don't install them. The idea is below. It strikes me as really ugly. I bet python has a nicer way to do this, but haven't found anything.

P.S. I know this idea doesn't work 100% , but it's just an illustration of the best approach I could think of.

import os
import cv2

def boke():
   with open('list.txt') as file:
      lines = file.readlines()
   return lines

os.system("pip3 list > list.txt")
l = boke()
if "cv2" in l == false:
   os.system("pip3 install cv2")
SlightlyKosumi
  • 701
  • 2
  • 8
  • 24
  • 1
    You could try to catch `ImportError`. But what you're suggesting would necessarily be ugly, not cute. – kaya3 Oct 13 '22 at 15:36
  • 1
    you can generate a reuirements.txt file with the list of needed packages to run your program. you can then install from this list. If packages are already installed nothing will happen, otherwise the missing ones will be installed. take a look at https://stackoverflow.com/questions/31684375/automatically-create-requirements-txt –  Oct 13 '22 at 15:45
  • To be honest, what that question is suggesting appears to me to be just a package which would more or less do what my program was suggesting. How does pip tell which packages are actually installed, I presume there is a json file somewhere that stores the info – SlightlyKosumi Oct 13 '22 at 18:24

0 Answers0