-2

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?

  • 1
    i think this was solved here. https://stackoverflow.com/questions/44210656/how-to-check-if-a-module-is-installed-in-python-and-if-not-install-it-within-t – jairoar Sep 03 '20 at 18:23

2 Answers2

0

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.

Jasar Orion
  • 626
  • 7
  • 26
0

You can use the subprocess module to execute pip list to get a list of the installed modules and check if it contains the pyodbc module.

import subprocess

module_list = subprocess.check_output(['pip', 'list'])

if b'pyodbc' in module_list:
    import pyodbc
    # your code here
flimosch
  • 36
  • 3