User:Msiddalingaiah/Python snippets

From Wikipedia, the free encyclopedia

A short collection of Python code snippets

Contents

[edit] Main function

if __name__ == "__main__":
    main()

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

[edit] Reading from a file

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

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