Python 3.4
Legacy Docs
Overview
This Quickstart covers using Python to create applications that can use Oracle. According to nearly all of the language tracking indices Python is one of the fastest growing and mature computer languages. It is also clearly the language to learn at this time.
There are some really good reasons to use Python:
- Python is fast, simple, powerful and scalable.
- Python works really well with databases especially Oracle.
- On average, Python scripts take 20% less code than other scripting languages and are still more readable!
- Because of the above Python has become one of the top enterprise scripting languages.
There is a plethora of draconian information on Python and tkinter. tkinter has been revamped and integrated with Python. Many may be surprised to find out that tkinter is the simplest most powerful GUI API for standard Python applications at this point.
When using Google preface your searches with the latest versions to get the most useful results. Example: "python 3" "tkinter 8.5"
Prerequisites
- Download software from Python.org.
Example file name of install: python-3.4.1.amd64.msi - Download the Oracle extension module matching your Python and Oracle version.
Example file: cx_Oracle-5.1.3-12c.win-amd64-py3.4.exe - Create directory for your applications.
Example: C:\app\py
Useful Links
- Python 3.x: Docs | Functions | Oracle Best Practices
- tkinter 8.5: Docs|Cmds|Library|Ref|Cfg|Wikipedia|examples
- Extensions: Create Windows .exe (cx-freeze) | PSUtil | tkRAD | Win32
- Tools: Py GUI Builder | Nullege.com | Django (Web via Python)
Python Installation
Linux (RHEL)
As root:
- Install package with repository for your system.
$ yum install centos-release-scl - Enable RHSCL repository for you system.
$ yum-config-manager --enable rhel-server-rhscl-7-rpms - Install the python collection.
$ yum install rh-python35 - Start using software collections.
$ scl enable rh-python35 bash
Windows
Run python-3.4.1.amd64.msi:
- (x) Install for all users.
- Destination Directory: C:\Python34 (use default)
- Customize
Accept defaults and add: Add python.exe to Path
Installation runs... - Finish
Test Python
From a command prompt window run: python -V
Python 3.4.1
If you dont see the above on a Windows system. Re-save the PATH variable. In some Windows environments it does not immediately detect the change to the PATH as added from the installer.
Install Python Extensions for Windows (AKA Win32 Extension)
This extension is not essential but incredibly useful. Should be part of your baseline in Windows environments.
- Run installation .exe.
Example: pywin32-219.win-amd64-py3.4.exe - Location
- Python Directory: C:\Python34 (default)
- Installation Directory: C:\Python34\Lib\site-packages\ (default) - Finish
If fields not filled in with defaults you most likely are trying to install wrong version.
Create a Test Application
- Go to your
C:\app\python
directory. - Create a file with the contents shown below as hello.py.
print("Hello World!")
- Run it by entering:
python hello.py
- You should see the famous Hello World! message displayed.
Install Oracle Extension Module
- Run installation .exe.
Example: cx_Oracle-5.1.3-12c.win-amd64-py3.4.exe - Location
- Python Directory: C:\Python34 (default)
- Installation Directory: C:\Python34\Lib\site-packages\ (default) - Finish
If fields not filled in with defaults you most likely are trying to install wrong version.
Test Oracle
import os import cx_Oracle # If IC On Same System as Database #os.putenv('ORACLE_HOME','C:\app\oracle\product\12.1.0\ic32') #os.putenv('ORACLE_SID','DB01') #os.putenv('TNS_ADMIN','C:\app\oracle\product\11.2.0.3\dbhome_1\\NETWORK\ADMIN') #Note the two(2) back slashes before \\NETWORK! # Connect print('Connecting...\n') connstr = 'scott/tiger@localhost:1521/DB01' connect = cx_Oracle.connect(connstr) #connect = cx_Oracle.connect(connstr,mode=cx_Oracle.SYSDBA) # Cursor sql = 'SELECT table_name FROM dba_tables ORDER BY table_name' curs = connect.cursor() curs.execute(sql) # Retrieve Just One Value for row in curs.fetchone(): print(row[0]) # Retrieve Multiple Values rows = curs.fetchall() for row in rows: print(row[0]) # End curs.close() connect.close() print('*** Program Ended ***\n')
Run Within Notepad++
-- Create Run Item
Press F6 then enter the below matching your environment.
NPP_SAVE cd "$(CURRENT_DIRECTORY)" python.exe $(NAME_PART).py
Save as: Python Run
-- Create NppExec Item
Go to Advance Options within NppExec plugin,
A. Check the box at the top that says "Place to the Macros Submenu" B. Select script from "Associated Script" combo box. It will automatically fill in the "Item Name". C. Now click the "Add/Modify" button. D. Click OK. This will exit the Advanced Options box and say that NotePad++ needs to be restarted.
-- Assign to HotKey
A. Navigate to: Settings -> Shortcut Mapper -> Plugin Commands -> Python Run B. Right-Click -> Modify C. Select Ctrl-F1 (or other combo you desire)
Notepad++ If Using Instant Client on DB Server
NPP_SAVE ENV_SET PATH = $(SYS.PATH);C:\Python34;C:\app\oracle\product\12.1.0.1\ic32; ENV_SET ORACLE_SID=DB01 ENV_SET ORACLE_HOME=c:\app\oracle\product\12.1.0.1\ic32; ENV_SET TNS_ADMIN=C:\app\oracle\product\11.2.0.3\dbhome_1\NETWORK\ADMIN; cd "$(CURRENT_DIRECTORY)" python.exe $(NAME_PART).py
With Notepad++ you can create a comment block highlighting a range and using:
Ctl-K = Comment Block Ctl-Shift-K = UN-comment Comment Block
Syntax Code Convention
Most Python variables can be summarized as: Strings, Numbers, Boolean, Arrays (AKA Lists) and instances of Objects (AKA classes).
- Variables: Proper case with prefix. Examples: aStates = ['FL','NY','TX'] nCount = 42 bActive = False sConn = 'scott/tiger@localhost:1521/DB01' oConn = cx_Oracle.connect(sConn) sSqlCmd = 'SELECT table_name FROM dba_tables ORDER BY table_name' oCursor = oConn.cursor() oCursor.execute(sSqlCmd) Note: Using an 'o' prefix for objects allows you to easily distinguish between native Python names. - GLOBAL variables: UPPER_CASE_WITH_UNDERSCORES Example: aSCHEMA - Classes: oMixedCase oEmail.Server = 10.10.10.1 # Property (Proper Case) oEmail.send # Method (lower case) SomeClass.doSomething # Complex Method Format: lowerProper e.g. actionNoun Note: Many Python developers simply prefer variable names just be a lower case name with underscores.
Symbolic Links Note
You can use symlinks if you have modules in a particular path and dont want to use an environment var or hard code an import path to access them. This is useful testing different versions of libs\modules.
Say you have the file c:\app\py\lib\utl.py and you want to link to it from here (c:\app\py\dev\myapp\utl.py) to access it as if it is local to that directory.
- From console window change to local dir.
cd c:\app\py\dev\myapp - Issue mklink command.
Creating a Stand-Alone Windows Version using cx_freeze
You may need MS Visual C++ 2010 Redist Pkg if not already installed.
Usage:
- Install cx_freeze Python extension.
- Create setup.py as shown below in the same folder as your script(s).
- Change to your script folder.
- Create build folder:
python setup.py build
- Copy the contents of you build folder to your destination system.
import sys from cx_Freeze import setup, Executable sBase = None aIncludeFiles = ["favicon.ico"] if sys.platform == "win32": sBase = "Win32GUI" aExecParams = [Executable('MyAppName.py',base=sBase)] setup(name="MyAppName", version="2.1", description="My GUI application!", executables=aExecParams, options = {'build_exe': {'include_files':aIncludeFiles} } )
If your application has any print or flush commands you may get a console window.