1

I need to connect to a test server and run a sql query using pyodbc. For that I first need to set ODBCINI environment variable. I tried including that in python code using subprocess.

import subprocess
import pyodbc

bashCommand = "export ODBCINI=~/odbc.ini"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE, shell=True)

pyodbc.pooling = False
conn = pyodbc.connect(DSN='test',autocommit=True,ansi=True)
cur = conn.cursor()

Below is the error I get

Traceback (most recent call last):
  File "my_si_web_impressions_bcookie_dealid.py", line 15, in <module>
    conn = pyodbc.connect(DSN='tdwb',autocommit=True,ansi=True)
pyodbc.Error: ('IM002', '[IM002] [DataDirect][ODBC lib] System information file not found. Please check the ODBCINI environment variable. (0) (SQLDriverConnect)')

I guess it implies that it din't export the ODBCINI variable so it couldn't connect to server. Can anyone help?

1 Answer 1

1

This doesn't work as you intend because a subprocess that is spawned can only affect it's own environment, and thus the one of the processes it spawns (as they inherit it).

So your bash-command is essentially a NOP.

Instead, you need to manipulate your own environment, by using os.environ:

 import os
 os.environ["ODBCINI"]="~/odbc.ini"

Then your connect should work.

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

6 Comments

I tried with this. #!/usr/bin/env python import pyodbc import os os.environ["ODBCINI"]="~/odbc.ini" pyodbc.pooling = False conn = pyodbc.connect(DSN='test',autocommit=True,ansi=True) cur = conn.cursor() Still same error Traceback (most recent call last): File "temp.py", line 8, in <module> conn = pyodbc.connect(DSN='test',autocommit=True,ansi=True) pyodbc.Error: ('IM002', '[IM002] [DataDirect][ODBC lib] System information file not found. Please check the ODBCINI environment variable. (0) (SQLDriverConnect)')
It might be that you need to call os.expanduser on the argument. Or give it as full path, e.g. "/home/foobar/odbc.ini"
And the obvious question: does the file exist? Try putting a statment "assert os.path.exists(os.environ['ODBCINI'])" after the setting of the variable.
Yeah, file exists. If I run the command on shell it works. and echo $ODBCINI shows the file path but after running it through python script echo $ODBCINI returns empty string. I have tried giving absolute path also. Doesn't work
Does the assert I mention work? And I don't understand the "running through python-script". What happens if you export the ODBCINI before invoking python, not making the os.environ-manipultion within the script?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.