user2004245 user2004245 - 3 months ago 30
Python Question

Setup cx_Oracle Environmental Variables with Python

cx_Oracle for Python requires certain Environmental Variables to be set in place to import and work correctly. Rather than trying to wrap my application in a bash script, which I've done in the past, I'm trying to setup the variables using only Python.

Below is what I have in place so far.

# Check if OS environment variables are setup.
if 'ORACLE_HOME' not in os.environ.keys():
os.environ['ORACLE_HOME'] = '/usr/lib/oracle/12.1/client64'
if 'LD_LIBRARY_PATH' not in os.environ.keys():
os.environ['LD_LIBRARY_PATH'] = os.environ['ORACLE_HOME'] + '/lib'
if '/usr/lib/oracle' not in os.environ['PATH']:
os.environ['PATH'] = os.environ['ORACLE_HOME'] + '/bin:' + os.environ['PATH']

import cx_Oracle

Unfortunately I'm still receiving the exception from cx_Oracle that basically means the variables are not setup properly.

I've also attempted using
to call the exports directly, but I'm not sure if they are just not working or I'm not understanding those functions correctly.

What is the best way to setup these variables so that I can import cx_Oracle using just Python 3.

Edit, Below is what I typically add to my bash wrappers:


# Initialize Environmental Variables for cx_Oracle
export ORACLE_HOME=/usr/lib/oracle/12.1/client64

(Python Script)


It is likely this question has been already answered on this site: How to change environment variables in python? I am quoting the accepted answer:

You can set them that way, however $LD_LIBRARY_PATH is read by the loader which has already run before that therefore you must set that one externally beforehand.