Jump to content

User:Msiddalingaiah/Python snippets

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

A short collection of Python code snippets

Main function

if __name__ == "__main__":
    main()

Command line arguments

import sys
for arg in sys.argv:
    print arg

sys.argv[0] is the command, sys.argv[1] is the first argument proper.

Reading from a file

f = open('attach.rtf', 'rt')
template = f.read()
f.close()

ODBC

import dbi, odbc
   conn = odbc.odbc('mydsn')
   cur = conn.cursor()
   cur.execute('select * from table1')
   list = []
   rec = cur.fetchmany(1)
   while rec:
       list.append(rec[0])
       rec = cur.fetchmany(1)
   cur.close()
   conn.close()
   for row in list:
       id = row[0]
       name = row[1]
       date = row[8]
       print '%s %s, %s' % (id, name, date)