Äîêóìåíò âçÿò èç êýøà ïîèñêîâîé ìàøèíû. Àäðåñ îðèãèíàëüíîãî äîêóìåíòà : http://www.stsci.edu/hst/training/events/Python/class5.pdf
Äàòà èçìåíåíèÿ: Wed Jun 15 23:09:13 2005
Äàòà èíäåêñèðîâàíèÿ: Sun Dec 23 00:37:23 2007
Êîäèðîâêà:

Ïîèñêîâûå ñëîâà: polar ring
STSCI Python Introduction

Class 5 Jim Hare

Today's Agenda
· · · · · · stpydb Module ­ database interface module os Module ­ commonly used methods os.path Module ­ Manipulates pathnames shutil Module - High-level file operations Demonstration of Pmw Widgets Simple helloworld Tkinter program

1


Database Functions
· dbtools.py ­ use with sql flat files. · stpydb.py ­ use to program queries and get results in variables to use in the module.

stpydb Functions
· stpydb() - Connecting to the database. stpydb is a class object. · getParamModeChar - Returns the query param substitution char · setParamModeChar - Defines the query param substitution char · setParam - Defines value for a named parameter · execute - Executes the query returning one row at a time · executeAll - Executes the query returning all rows · executeUpdate - Executes an update/insert/delete query

2


stpydb Functions continued
· rowcount - Returns #rows affected by a query · beginTransaction - Starts a transaction on a given connection · commitTransaction - Commits a transaction on a given connection · rollbackTransaction - Aborts a transaction on a given connection · clear - Clears an unfinished query

stpydb Functions continued
· getDescription - Returns meta data info on last select query · printDescription - Prints meta data report on last select query · query - Pass a query string · close - Shuts down the connection

3


stpydb Constructor
· Look at def __init__ in /ess5/psdpython/stpydb.py, the constructor · Examples: q1 = stpydb.stpydb() q2 = stpydb.stpydb('NOMAD') q3 = stpydb.stpydb(dbmsName='psttest4') q4 = stpydb.stpydb('NOMAD','psttest4') q5 = stpydb.stpydb(moduleName='testpydb.py') q6 = stpydb.stpydb('R2D2','pstdev1','testpydb.py')

Parameters, Queries and Execution - executeUpdate
· Ex. Update ­ from /ess5/psdpython/spssdb.py
db= stpydb.stpydb(serverName=server,dbmsName=database) param = [['PROP', proposal_id],['OBSET', obset_id], ['BEG',window_beg], ['END',window_end]] db.query('update qbwindows set window_beg = @BEG, ' 'window_end = @END where proposal_id = @PROP ' 'and obset_id = @OBSET') db.setParam(param) db.executeUpdate() return None

4


Parameters, Queries and Execution - execute
· Ex. Execute ­ returns one record at a time
param = ['sunit',suId[0]] db.query('select qs.proposal_id,qs.obset_id') db.query(' from qsbranching qs ') db.query('where qs.sunit_id = @sunit') db.setParam(param) result = {} while db.execute(result): obsetList = obsetList + \ ['%s:%s:01' % (result['proposal_id'],result['obset_id'])]

Parameters, Queries and Execution - executeAll
· Ex. executeAll ­ returns list of records currlist = [{}] q1.query("select d_scenar_acq, d_use_fgs_1, d_use_fgs_2, d_use_fgs_3 ") q1.query("from qbacqd_def") q1.executeAll(currlist) for currdict in currlist: for field in currdict.keys(): print currdict[field]

5


Transactions
· q3.beginTransaction() q3.query(querynew1) q3.executeUpdate() q3.query(querynew2) q3.executeUpdate() #NO error condition if you don't rollback! q3.rollbackTransaction()

Tools and Examples
­ spssdb.py ­ functions related to spss database ­ siRecon.py ­ a tool to get 10.2 table data ­ stpydb.py ­ the tool developed for sybase interface ­ testpydb.py ­ tests developed to test stpydb

6


os Module Functions
· · · · · General Purpose Process Environment Files and Directories Process Management os.path - manipulates pathnames in a portable manner.

General Purpose os Variables
· environ - mapping object of the current environment variables. · linesep - `\n' for POSIX · name - `posix','nt','dos','mac', or `os2' · path - OS-dependent standard module for pathname operations

7


Process Environment os Functions Highlights
· chdir(path) - changes the current working dir to path · getcwd() - gets the current working dir · getpid() - get the process id of process · getuid() - get the user id of current process · putenv(varname, value) - Changes subprocess environment variable varname. · uname() - returns (sysname,nodename,release,version,machine)

File and Directory os Highlights
· chmod(path, mode) - changes access mode · access(path,accessmode) - returns 1 if ok Accessmode - R_OK,W_OK,X_OK, or F_OK · listdir(path) - List of filename returned · mkdir(path, [mode]) - create directory · mkdirs(path, [mode]) - makes directories to reach the leaf, recursive

8


Files and Directories os cont.
· · · · · remove(path) - remove the file path removedirs(path) - recursive removal rename(src, dst) - renames src to dst renames(old, new) - recursive rename rmdir(path) - removes the path

Process Management os Functions Higlights
· exec'l','le','lp','v','ve','vp','vpe' - Many ways to execute a program path. · fork() - creates a clone child process. · spawn'v',or've'(mode, path, args) (env) spawns a program path in a new process · system(command) - executes a system command in a subprocess

9


os.path Module Highlights
· abspath(path) - absolute full pathname abspath(`../Python/foo') is `/home/bz/Python/foo' · basename(path) - returns the basename basename(`/usr/local/python') is `python'. · dirname(path) - directory of the path dirname(`/usr/local/python') is `/usr/local' · split(path) - returns tuple (dirname(),basename())

os.path Module Highlights cont.
· · · · exists(path) - true if path exists isfile(path) - true if path is regular file isdir(path) - true if path is a directory join(path1,[,path2[,...]]) - intelligent join of one or mor paths join(`/home','bz','Python') is `/home/bz/Python' · splitext(path) - splitext(`foo.txt') is (`foo','txt')

10


shutil Module Highlights
· copy(src, dst) - copies from src to dst and permissions. · Other copys - copyfile, copymode, copystat, copy2 · copytree(src, dst [, symlinks]) - recursively copies an entire directory tree. dst will be created and should not exist. Sylinks - true - symlinks same in the new tree; false - contents of linked files are copied to the new directory tree. · rmtree(path, [, ignore_errors[, onerror]]) - remove directory tree

Pmw Demo
What's a Widget?

11


Tkinter helloWorld Program
A simple example of Tkinter

12