User:Msiddalingaiah/Python snippets

From Wikipedia, the free encyclopedia

A short collection of Python code snippets

Main function[edit]

if __name__ == "__main__":
    main()

Command line arguments[edit]

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[edit]

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

ODBC[edit]

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)