I have a Python script that export some data from mssql server. I use the pyodbc module. Before i run my Python script i want to check if the pyodbc modules exists and if not to install it as we do with pip install pyodbc. What is the correct approach to do this?
2 Answers
i did in this way:
import os
while True:
try:
import pyodbc
print("pyodbc imported")
break
except:
print(os.popen("pip install pyodbc").read())
continue
print("the rest of your script here")
when you run this code the output is:
C:\projects>python autoinstall.py
WARNING: You are using pip version 20.2.1; however, version 20.2.2 is available.
You should consider upgrading via the 'c:\python38-32\python.exe -m pip install --upgrade pip' command.
Collecting pyodbc
Using cached pyodbc-4.0.30-cp38-cp38-win32.whl (58 kB)
Installing collected packages: pyodbc
Successfully installed pyodbc-4.0.30
pyodbc imported
the rest of your script here
in this way it will install any missing module and start the code in one run.