Search code examples
pythonpython-3.xshellcroncx-oracle

Connection to Oracle db (cx_Oracle) not working when scheduled from crontab but works as standalone


I have a python (3.6) script that does some things with data retrieved from Oracle DB. Then I have a shell script for automation that execute the script. I than schedule the execution of such shell in crontab.

If I execute the shell as standalone (sh shell.sh) it works perfectly fine, while when it runs as a crontab job connection to Oracle DB fails --> class 'cx_Oracle.DatabaseError'

I'm trying to simplify the code I'm using, the Python script is as follow:

#!/usr/bin/python3.6
# coding: utf-8
import pandas as pd
import cx_Oracle
try:
    conn = cx_Oracle.connect(username/pwd@hostname:port/db_name)
    query = """SELECT * FROM schema.table"""
    df = pd.read_sql(query, con = conn)
except:
    print(sys.exc_info()[0])
    raise
    sys.exit(1)

The shell is doing something like this:

#!/usr/bin/env bash
if [something]
then
    python3.6 pyscript.py
fi

The crontab -l result:

* * * * * cd /root/workindirectory ; sudo sh shell.sh >> test.out

Thank you all in advance for any help.

EDIT: to specify that both shell and python scripts have 777 permissions


Solution

  • I'm sorry as I think this was a duplicate of cx_Oracle Package Not working inside Crontab

    As cron does not load bash profile, I've found a solution exporting ORACLE_HOME and LD_LIBRARY_PATH in the shell script. As pointed out in the linked question, the lines to be added are:

    export ORACLE_HOME=/usr/lib/oracle/<version>/client(64)
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH