I needed to write a new script that was running on a Red Hat Linux 6 virtual machine and that would connect to databases using SQL*Plus. I was going to write a bash shell script but decided to use Python instead to see if I could do it using the Python that came with this version of Linux. I wont paste the entire script here but the key was to run SQL*Plus from Python instead of a shell script. Here is a simple example showing how I did it:
Here is the output:
$ python test.py SQL*Plus: Release 22.214.171.124.0 Production on Fri Nov 4 15:44:30 2016 Copyright (c) 1982, 2014, Oracle. All rights reserved. SQL> SQL> Connected. SQL> D - X SQL> Disconnected from Oracle Database 12c Enterprise Edition Release 126.96.36.199.0 - 64bit Production With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options
The function run_sqlplus takes a multi-line string as input. This is the text of a SQL*Plus script. It runs sqlplus /nolog to get a SQL*Plus prompt and then passes the strings in as the lines typed at the prompt. The function returns SQL*Plus’s output as a list of strings.
Anyway, this is just an example. I built a real script using these concepts. In this case we are using Python 2.6.6 without cx_Oracle installed so I couldn’t connect directly to an Oracle database. Instead I just ran SQL*Plus from Python.
P.S. I edited this on 2/12/2018 to make it work with both Python 2 and 3. I added the encode and decode and made the print statement use parentheses.