-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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.