initial creation

This commit is contained in:
2025-05-20 11:57:43 -04:00
commit c98b612926
8447 changed files with 1862526 additions and 0 deletions
@@ -0,0 +1,32 @@
#!/usr/bin/env python
#
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta): # <1>
@abstractmethod # <2>
def speak(self):
pass
class Dog(Animal): # <3>
def speak(self): # <4>
print("woof! woof!")
class Cat(Animal): # <3>
def speak(self): # <4>
print("Meow meow meow")
class Duck(Animal): # <3>
pass # <5>
d = Dog()
d.speak()
c = Cat()
c.speak()
try:
d = Duck() # <6>
d.speak()
except TypeError as err:
print(err)
@@ -0,0 +1,28 @@
#!/usr/bin/env python
from types import MethodType
class Dog(): # <1>
pass
d1 = Dog() # <2>
def bark(self): # <3>
print("Woof! woof!")
setattr(Dog, "bark", bark) # <4>
d2 = Dog() # <5>
d1.bark() # <6>
d2.bark()
def wag(self): # <7>
print("Wagging...")
setattr(d1, "wag", MethodType(wag, d1)) # <8>
d1.wag() # <9>
try:
d2.wag() # <10>
except AttributeError as err:
print(err)
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python
class Animal():
count = 0 # <1>
def __init__(self, species, name, sound):
self._species = species
self._name = name
self._sound = sound
Animal.count += 1
@property
def species(self):
return self._species
@classmethod
def kill(cls):
cls.count -= 1
@property
def name(self):
return self._name
def make_sound(self):
print(self._sound)
@classmethod
def remove(cls):
cls.count -= 1 # <2>
@classmethod
def zoo_size(cls): # <3>
return cls.count
if __name__ == "__main__":
leo = Animal("African lion", "Leo", "Roarrrrrrr")
garfield = Animal("cat", "Garfield", "Meowwwww")
felix = Animal("cat", "Felix", "Meowwwww")
print(leo.name, "is a", leo.species, "--", end=' ')
leo.make_sound()
print(garfield.name, "is a", garfield.species, "--", end=' ')
garfield.make_sound()
print(felix.name, "is a", felix.species, "--", end=' ')
felix.make_sound()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python
class Spam():
def eggs(self, msg): # <1>
print("eggs!", msg)
s = Spam()
s.eggs("fried")
print("hasattr()", hasattr(s, 'eggs')) # <2>
e = getattr(s, 'eggs') # <3>
e("scrambled")
def toast(self, msg):
print("toast!", msg)
setattr(Spam, 'eggs', toast) # <4>
s.eggs("buttered!")
delattr(Spam, 'eggs') # <5>
try:
s.eggs("shirred")
except AttributeError as err: # <6>
print(err)
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python
"""Basic sorting example"""
fruit = ["pomegranate", "cherry", "apricot", "date", "Apple", "lemon", "Kiwi",
"ORANGE", "lime", "Watermelon", "guava", "papaya", "FIG", "pear", "banana",
"Tamarind", "persimmon", "elderberry", "peach", "BLUEberry", "lychee",
"grape"]
sorted_fruit = sorted(fruit) # <1>
print(sorted_fruit)
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python
from struct import Struct
values = 7, 6, 42.3, b'Guido' # <1>
demo = Struct('iif10s') # <2>
print("Size of data: {} bytes".format(demo.size)) # <3>
binary_stream = demo.pack(*values) # <4>
int1, int2, float1, raw_bytes = demo.unpack(binary_stream) # <5>
str1 = raw_bytes.decode().rstrip('\x00') # <6>
print(raw_bytes)
print(int1, int2, float1, str1)
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python
a = 0b10101010 # <1>
b = 0b11110000
c = a & b # <2>
print(" {:08b}".format(a))
print("& {:08b}".format(b))
print(" --------")
print(" {:08b}".format(c))
print()
c = a | b # <3>
print(" {:08b}".format(a))
print("| {:08b}".format(b))
print(" --------")
print(" {:08b}".format(c))
print()
c = a ^ b # <4>
print(" {:08b}".format(a))
print("^ {:08b}".format(b))
print(" --------")
print(" {:08b}".format(c))
print()
c = ~a # <5>
print(" ~ {:09b}".format(a))
print(" {:09b}".format(c))
print()
c = a >> 1 # <6>
print("{:08b} >> 1".format(a))
print("{:08b}".format(c))
print()
c = a >> 3 # <7>
print("{:08b} >> 3".format(a))
print("{:08b}".format(c))
print()
c = a << 1 # <8>
print("{:012b} << 1".format(a))
print("{:012b}".format(c))
print()
c = a << 3 # <9>
print("{:012b} << 3".format(a))
print("{:012b}".format(c))
print()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python
import timeit
setup_code = 'values = []' # <1>
test_code_one = '''
for i in range(10000):
values.append(i)
''' # <2>
test_code_two = '''
i = 0
while i < 10000:
values.append(i)
i += 1
''' # <2>
t1 = timeit.Timer(test_code_one, setup_code) # <3>
t2 = timeit.Timer(test_code_two, setup_code) # <3>
print("test one:")
print(t1.timeit(1000)) # <4>
print()
print("test two:")
print(t2.timeit(1000)) # <4>
print()
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import os
import calendar
import webbrowser
hcal = calendar.HTMLCalendar() # <1>
formatted_month = hcal.formatmonth(2012, 1) # <2>
html_file_name = 'sample_calendar.html'
with open(html_file_name, 'w') as calendar_out:
calendar_out.write(formatted_month) # <3>
webbrowser.open("file://" + os.path.realpath(html_file_name)) # <4>
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python
import calendar
tcal = calendar.TextCalendar() # <1>
print(tcal.formatmonth(2012, 1)) # <2>
print()
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python
class HTMLWrapper():
def __init__(self, tag):
self._tag = tag
def __call__(self, text): # <1>
return '<{0}>{1}</{0}>'.format(self._tag, text)
if __name__ == '__main__':
h1 = HTMLWrapper('h1') # <2>
print(h1('spam')) # <3>
div = HTMLWrapper('div')
print(div('ham'))
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python
class Rabbit:
LOCATION = "the Cave of Caerbannog" # <1>
def __init__(self, weapon):
self.weapon = weapon
def display(self):
print("This rabbit guarding {} uses {} as a weapon".
format(self.LOCATION, self.weapon)) # <2>
r1 = Rabbit("a nice cup of tea")
r1.display() # <3>
r1 = Rabbit("big pointy teeth")
r1.display() # <3>
@@ -0,0 +1,20 @@
#!/usr/bin/env python
class Rabbit:
LOCATION = "the Cave of Caerbannog" # <1>
def __init__(self, weapon):
self.weapon = weapon
def display(self):
print("This rabbit guarding {} uses {} as a weapon".
format(self.LOCATION, self.weapon)) # <2>
@classmethod # <3>
def get_location(cls): # <4>
return cls.LOCATION # <5>
r = Rabbit("a nice cup of tea")
print(Rabbit.get_location()) # <6>
print(r.get_location()) # <7>
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env python
import sys # <1>
print(sys.argv) # <2>
name = sys.argv[1] # <3>
print("name is", name)
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python
from collections import Counter
with open("../DATA/breakfast.txt") as breakfast_in:
foods = [line.rstrip() for line in breakfast_in] # <1>
counts = Counter(foods) # <2>
for item, count in counts.items(): # <3>
print(item, count)
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python
counts = {} # <1>
with open("../DATA/breakfast.txt") as breakfast_in:
for line in breakfast_in:
breakfast_item = line.rstrip('\n\r')
if breakfast_item in counts: # <2>
counts[breakfast_item] = counts[breakfast_item] + 1 # <3>
else:
counts[breakfast_item] = 1 # <4>
for item, count in counts.items():
print(item, count)
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python
def function_1(self): # <1>
print("Hello from f1()")
def function_2(self): # <1>
print("Hello from f2()")
NewClass = type("NewClass", (), { # <2>
'hello1': function_1,
'hello2': function_2,
'color': 'red',
'state': 'Ohio',
})
n1 = NewClass() # <3>
n1.hello1() # <4>
n1.hello2()
print(n1.color) # <5>
print()
SubClass = type("SubClass", (NewClass,), {'fruit': 'banana'}) # <6>
s1 = SubClass() # <7>
s1.hello1() # <8>
print(s1.color) # <9>
print(s1.fruit)
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env python
import csv
field_names = ['term', 'firstname', 'lastname', 'birthplace', 'state', 'party'] # <1>
with open('../DATA/presidents.csv') as presidents_in:
rdr = csv.DictReader(presidents_in, fieldnames=field_names) # <2>
for row in rdr: # <3>
print('{:25s} {:12s} {}'.format(row['firstname'], row['lastname'], row['party'])) # <4>
# string .format can use keywords from an unpacked dict as well:
# print('{firstname:25s} {lastname:12s} {party}'.format(**row))
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env python
import csv
with open('../DATA/computer_people.txt') as computer_people_in:
rdr = csv.reader(computer_people_in, delimiter=';') # <1>
for first_name, last_name, known_for, birth_date in rdr: # <2>
print('{}: {}'.format(last_name, known_for))
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python
import csv
with open('../DATA/knights.csv') as knights_in:
rdr = csv.reader(knights_in) # <1>
for name, title, color, quest, comment, number, ladies in rdr: # <2>
print('{:4s} {:9s} {}'.format(
title, name, quest
))
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python
import sys
import csv
data = [
('February', 28, 'The shortest month, with 28 or 29 days'),
('March', 31, 'Goes out like a "lamb"'),
('April', 30, 'Its showers bring May flowers'),
]
with open('../TEMP/stuff.csv', 'w') as stuff_in:
if sys.platform == 'win32':
wtr = csv.writer(stuff_in, lineterminator='\n') # <1>
else:
wtr = csv.writer(stuff_in) # <1>
for row in data:
wtr.writerow(row) # <2>
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python
fruit = ["pomegranate", "cherry", "apricot", "date", "Apple", "lemon",
"Kiwi", "ORANGE", "lime", "Watermelon", "guava", "papaya", "FIG",
"pear", "banana", "Tamarind", "persimmon", "elderberry", "peach",
"BLUEberry", "lychee", "grape"]
def ignore_case(item): # <1>
return item.lower() # <2>
fs1 = sorted(fruit, key=ignore_case) # <3>
print("Ignoring case:")
print(" ".join(fs1), end="\n\n")
def by_length_then_name(item):
return (len(item), item.lower()) # <4>
fs2 = sorted(fruit, key=by_length_then_name)
print("By length, then name:")
print(" ".join(fs2))
print()
nums = [800, 80, 1000, 32, 255, 400, 5, 5000]
n1 = sorted(nums) # <5>
print("Numbers sorted numerically:")
for n in n1:
print(n, end=' ')
print("\n")
n2 = sorted(nums, key=str) # <6>
print("Numbers sorted as strings:")
for n in n2:
print(n, end=' ')
print()
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
# (c) 2016 John Strickler
#
def get_primes(int kmax):
cdef int n, k, i, max=kmax
cdef int p[100000]
result = []
if kmax > 100000:
kmax = 100000
k = 0
n = 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i = i + 1
if i == k:
p[k] = n
k = k + 1
result.append(n)
n = n + 1
return result
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import time
import py_primes
import numba_primes
import pyximport
pyximport.install() # <1>
import cy_primes # <2>
NUM_PRIMES = 5000 # <3>
for mod in numba_primes, cy_primes, py_primes: # <4>
timestamp = time.time() # <5>
prime_list = mod.get_primes(NUM_PRIMES) # <6>
timestamp2 = time.time() # <7>
elapsed = timestamp2 - timestamp # <8>
print(prime_list[:20], prime_list[-20:])
print("{} took {:.3f} seconds to find {} primes".format(
mod.__name__, elapsed, len(prime_list))) # <9>
print()
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
#
from dateutil import parser
date_strings = [ # <1>
'April 1, 2015',
'4/1/2015',
'Apr 1, 2015',
'Apr 1 2015',
'04/01/2015',
'1 Apr 2015',
'April 1st, 2015',
'April 1, 2015 8:09',
'4/1/2015 8:09 PM',
'Apr 1, 2015 5 AM',
'Apricot 4, 341',
]
for date_string in date_strings:
try:
dt = parser.parse(date_string) # <2>
print(dt)
except ValueError as err:
print("Can't parse", date_string)
@@ -0,0 +1,67 @@
#!/usr/bin/env python
from datetime import date, time, datetime
import time as Time
my_time = time(10, 42, 51) # <1>
my_date = date(1996, 1, 31) # <2>
my_datetime = datetime(1996, 1, 31, 10, 42, 51) # <3>
my_timestamp = my_datetime.timestamp() # <4>
my_timetuple = my_datetime.timetuple() # <5>
print("my_time:", my_time)
print("my_date:", my_date)
print("my_datetime:", my_datetime)
print("my_timestamp:", my_timestamp)
print("my_timetuple:", my_timetuple)
print()
d = my_datetime.date() # <6>
print("datetime -> date:", d)
t = my_datetime.time() # <7>
print("datetime -> time:", t)
ts = my_datetime.timestamp() # <8>
print("datetime -> timestamp:", ts)
tt = my_datetime.timetuple() # <9>
print("datetime -> timetuple:", tt)
print()
dt = datetime.fromordinal(my_date.toordinal()) # <10>
print("date -> datetime:", dt)
t = datetime.fromordinal(my_date.toordinal()).time() # <11>
print("date -> time:", t)
ts = datetime.fromordinal(my_date.toordinal()).timestamp() # <12>
print("date -> timestamp:", ts)
tt = my_date.timetuple() # <13>
print("date -> timetuple:", tt)
print()
dt = my_datetime.fromtimestamp(my_timestamp) # <14>
print("timestamp -> datetime:", dt)
d = my_datetime.fromtimestamp(my_timestamp).date() # <15>
print("timestamp -> date:", d)
t = my_datetime.fromtimestamp(my_timestamp).time() # <16>
print("timestamp -> datetime:", t)
tt = Time.localtime(my_timestamp)
print("timestamp -> timetuple:", tt) # <17>
print()
dt = datetime.fromtimestamp(Time.mktime(my_timetuple)) # <18>
print("timetuple -> datetime:", dt)
d = datetime.fromtimestamp(Time.mktime(my_timetuple)).date() # <19>
print("timetuple -> date:", d)
dt = datetime.fromtimestamp(Time.mktime(my_timetuple)) # <20>
print("timetuple -> time:", t)
ts = Time.mktime(my_timetuple) # <21>
print("timetuple -> timestamp:", ts)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python
from datetime import datetime, date, timedelta
print("date.today():", date.today()) # <1>
now = datetime.now() # <2>
print("now.day:", now.day) # <3>
print("now.month:", now.month)
print("now.year:", now.year)
print("now.hour:", now.hour)
print("now.minute:", now.minute)
print("now.second:", now.second)
d1 = datetime(2018, 6, 13) # <4>
d2 = datetime(2018, 8, 24)
d3 = d2 - d1 # <5>
print("raw time delta:", d3)
print("time delta days:", d3.days) # <6>
interval = timedelta(10) # <7>
print("interval:", interval)
d4 = d2 + interval # <8>
d5 = d2 - interval
print("d2 + interval:", d4)
print("d2 - interval:", d5)
print()
t1 = datetime(2016, 8, 24, 10, 4, 34) # <9>
t2 = datetime(2018, 8, 24, 22, 8, 1)
t3 = t2 - t1
print("datetime(2016, 8, 24, 10, 4, 34):", t1)
print("datetime(2018, 8, 24, 22, 8, 1):", t2)
print("time diff (t2 - t1):", t3)
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python
from datetime import datetime as DateTime
# Bill Gates's birthday
gates_bd = DateTime(1955, 10, 28, 22, 0, 0) # <1>
print(gates_bd) # <2>
print()
print(gates_bd.strftime('Bill was born on %B %d, %Y at %I:%M %p')) # <3>
print()
print(gates_bd.strftime('BG: %m/%d/%y')) # <3>
print()
print(gates_bd.strftime('Mr. Gates was born %d-%b-%Y')) # <3>
print()
print(gates_bd.strftime('log entry: %Y-%m-%d')) # <3>
print()
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python
from datetime import datetime as DateTime
import time
data = (
('Jan 1, 1970', '%b %d, %Y'),
('01/01/70', '%m/%d/%y'),
('1970-01-01', '%Y-%m-%d'),
('Jan 1, 1970 at 3:14 pm', '%b %d, %Y at %I:%M %p'),
)
for date_str, parse_template in data:
time_tuple = time.strptime(date_str, parse_template) # <1>
print(time_tuple)
print()
parsed_date = DateTime.strptime(date_str, parse_template) # <2>
print(parsed_date)
print('-' * 20)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import pymssql
conn = pymssql.connect(
host="host",
db="database",
user="username",
passwd="l0lz"
)
cursor = conn.cursor()
# select first name, last name from all presidents
row_count = cursor.execute('''
select lname, fname
from presidents
''')
print("{} rows in result set\n".format(row_count))
for row in cursor.fetchall():
print(' '.join(row))
print()
# cursor.fetchone() and cursor.fetchmany() are also available
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
from contextlib import closing
import pymysql
with closing(
pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts",
)
) as myconn:
mycursor = myconn.cursor()
# select first name, last name from all presidents
row_count = mycursor.execute('''
select firstname, lastname
from presidents
''')
print("{} rows in result set\n".format(row_count))
for firstname, lastname in mycursor.fetchall():
print(firstname, lastname)
print()
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import pymysql
import pymysql.cursors
myconn = pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts",
cursorclass=pymysql.cursors.DictCursor
)
c = myconn.cursor()
# call a stored proc two different ways
cur = myconn.cursor(pymysql.cursors.Cursor)
cur.execute('call pres_full_name(16)')
print(cur.fetchone())
cur.callproc('pres_full_name', (16,))
print(cur.fetchone())
myconn.close()
@@ -0,0 +1,30 @@
#!/usr/bin/env python
from contextlib import closing
import pymysql
# pymysql can't execute multiple statements, so we execute one at a time
sql_statements = [
"""DROP PROCEDURE IF EXISTS `pres_full_name`;""",
"""
CREATE PROCEDURE pres_full_name (IN term_num int)
BEGIN
select concat(firstname, ' ', lastname)
from presidents
where termnum = term_num;
END
""",
]
with closing(
pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts",
)
) as my_conn:
my_cursor = my_conn.cursor()
for sql_statement in sql_statements:
my_cursor.execute(sql_statement)
@@ -0,0 +1,29 @@
#!/usr/bin/env python
import pymysql
import pymysql.cursors
myconn = pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts",
cursorclass=pymysql.cursors.DictCursor
)
# c = myconn.cursor(pymysql.cursors.DictCursor)
c = myconn.cursor()
# select first name, last name from all presidents
num_recs = c.execute('''
select lastname, firstname
from presidents
''')
print(c.description)
for row in c.fetchall():
print(row['firstname'], row['lastname'])
print()
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python
import pymysql
DB = 'information_schema'
DB_HOST = 'localhost'
DB_USER = 'scripts'
DB_PASSWORD = 'scripts'
TABLE_QUERY = '''
select table_name
from tables
where table_schema = %s
'''
COLUMN_QUERY = '''
select column_name, data_type, is_nullable, column_default
from columns
where
table_name = %s
and
table_schema = %s
'''
def main(database_name):
mycursor = connect_to_dbserver()
tables = get_all_tables_from_database(mycursor, database_name)
print('-' * 60)
for table in tables:
print(table)
columns = get_columns_for_table(mycursor, table, database_name)
column_data_format = '\t{:15} {:12} {:3} {:10}'
for col_name, col_type, is_nullable, default_value in columns:
print(column_data_format.format(col_name, col_type, is_nullable, default_value))
def connect_to_dbserver():
with pymysql.connect(
host=DB_HOST,
db=DB,
user=DB_USER,
passwd=DB_PASSWORD
) as cursor:
return cursor
def get_all_tables_from_database(mycursor, database):
mycursor.execute(TABLE_QUERY, (database,))
return [row[0] for row in mycursor.fetchall()]
def get_columns_for_table(mycursor, table_name, database_name):
mycursor.execute(COLUMN_QUERY, (table_name, database_name))
return mycursor.fetchall()
if __name__ == '__main__':
main('python2')
@@ -0,0 +1,32 @@
#!/usr/bin/env python
from contextlib import closing
from collections import namedtuple
import pymysql
def named_tuple_cursor(cursor):
'''Generate rows as named tuple'''
column_names = [desc[0] for desc in cursor.description]
row_tuple = namedtuple('row_tuple', column_names)
# "row_tuple" is internal name of row_tuple class
for cursor_row in cursor.fetchall():
yield row_tuple(*cursor_row)
with closing(pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts",
)) as myconn:
c = myconn.cursor()
# select first name, last name from all presidents
num_recs = c.execute('''
select lastname, firstname
from presidents
''')
for row in named_tuple_cursor(c):
print(row.firstname, row.lastname)
@@ -0,0 +1,29 @@
#!/usr/bin/env python
from contextlib import closing
import pymysql
with closing(pymysql.connect(
host="localhost",
db="presidents",
user="scripts",
passwd="scripts"
)) as myconn:
mycursor = myconn.cursor()
for party_name in 'Whig', 'Federalist':
print(party_name.upper() + ':')
mycursor.execute('''
select lastname, firstname
from presidents
where party = %s
''', party_name)
print(mycursor.fetchall())
print()
print(mycursor.description)
# for row in mycursor.fetchall():
# print(row)
# print('-' * 60)
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
import psycopg2
pg_conn = psycopg2.connect(
host="localhost",
dbname="postgres",
user="postgres",
password='scripts',
)
pg_cursor = pg_conn.cursor()
# select first name, last name from all presidents
pg_cursor.execute('''
select firstname, lastname from presidents order by termnum
''')
print("{} rows in result set\n".format(pg_cursor.rowcount))
for row in pg_cursor.fetchall():
print(' '.join(row))
print()
pg_conn.close()
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python
import psycopg2
import psycopg2.extras
conn = psycopg2.connect(
host="localhost",
dbname="postgres",
user="postgres",
password='scripts',
)
c = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
c.execute('''
select * from presidents where termnum = %s
''', (26,))
row = c.fetchone()
print(row['firstname'], row['lastname'])
print('{0[firstname]} {0[lastname]} is a {0[party]}'.format(row))
@@ -0,0 +1,72 @@
#!/usr/bin/env python
import psycopg2
DB_HOST = 'localhost'
DB_USER = 'postgres'
DB_PASSWORD = 'scripts'
TABLE_QUERY = '''
select table_name
from information_schema.tables
where table_schema = 'public'
'''
COLUMN_QUERY = '''
select column_name, data_type, is_nullable, column_default
from information_schema.columns
where
table_name = %s
and
table_schema = 'public'
'''
def main(database_name):
try:
pgcursor = connect_to_dbserver(database_name)
except Exception as err:
print("Unable to connection to {}: {}".format(database_name, err))
tables = get_all_tables_from_database(pgcursor, database_name)
for table in tables:
print(table)
columns = get_columns_for_table(pgcursor, table, database_name)
if columns:
column_data_format = '\t{:15} {:20} {:3} {:10}'
for col_name, col_type, is_nullable, default_value in columns:
print(column_data_format.format(col_name, col_type, is_nullable, default_value))
def connect_to_dbserver(database_name):
try:
with psycopg2.connect(
host=DB_HOST,
dbname=database_name,
user=DB_USER,
password=DB_PASSWORD,
) as pgconn:
return pgconn.cursor()
except Exception as err:
print(err)
raise err
def get_all_tables_from_database(pgcursor, database):
pgcursor.execute(TABLE_QUERY, (database,))
return [row[0] for row in pgcursor.fetchall()]
def get_columns_for_table(pgcursor, table_name, database_name):
try:
pgcursor.execute(COLUMN_QUERY, (table_name,))
except psycopg2.ProgrammingError as err:
print("Unable to get columns:", err)
else:
return pgcursor.fetchall()
if __name__ == '__main__':
main('postgres')
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python
#
good_input = 'Google'
malicious_input = "'; drop table customers; -- " # <1>
naive_format = "select * from customers where company_name = '{}' and company_id != 0"
good_query = naive_format.format(good_input) # <2>
malicious_query = naive_format.format(malicious_input) # <2>
print("Good query:")
print(good_query) # <3>
print()
print("Bad query:")
print(malicious_query) # <4>
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python
import sqlite3
with sqlite3.connect("../DATA/presidents.db") as s3conn: # <1>
s3cursor = s3conn.cursor() # <2>
# select first name, last name from all presidents
s3cursor.execute('''
select firstname, lastname
from presidents
''') # <3>
print("Sqlite3 does not provide a row count\n") # <4>
for row in s3cursor.fetchall(): # <5>
print(' '.join(row)) # <6>
@@ -0,0 +1,96 @@
#!/usr/bin/env python
import os
import sqlite3
import random
FRUITS = ["pomegranate", "cherry", "apricot", "date", "apple",
"lemon", "kiwi", "orange", "lime", "watermelon", "guava",
"papaya", "fig", "pear", "banana", "tamarind", "persimmon",
"elderberry", "peach", "blueberry", "lychee", "grape"]
DB_NAME = 'fruitprices.db' # <1>
CREATE_TABLE = """
create table fruit (
name varchar(30),
price decimal
)
""" # <2>
INSERT = '''
insert into fruit (name, price) values (?, ?)
''' # <3>
def main():
"""
Program entry point.
:return: None
"""
conn = get_connection()
create_database(conn)
populate_database(conn)
read_database()
def get_connection():
"""
Get a connection to the PRODUCE database
:return: SQLite3 connection object.
"""
if os.path.exists(DB_NAME):
os.remove(DB_NAME) # <4>
s3conn = sqlite3.connect(DB_NAME) # <5>
return s3conn
def create_database(conn):
"""
Create the fruit table
:param conn: The database connection
:return: None
"""
conn.execute(CREATE_TABLE) # <6>
def populate_database(conn):
"""
Add rows to the fruit table
:param conn: The database connection
:return: None
"""
fruit_data = get_fruit_data() # [('apple', .49), ('kiwi', .38)]
try:
conn.executemany(INSERT, fruit_data) # <7>
except sqlite3.DatabaseError as err:
print(err)
conn.rollback()
else:
conn.commit() # <8>
def get_fruit_data():
"""
Create iterable of fruit records.
:return: Generator of name/price tuples.
"""
return ((f, round(random.random() * 10 + 5, 2)) for f in FRUITS) # <9>
def read_database():
conn = sqlite3.connect(DB_NAME)
for name, price in conn.execute('select name, price from fruit'):
print('{:12s} {:6.2f}'.format(name, price))
if __name__ == '__main__':
main()
@@ -0,0 +1,25 @@
#!/usr/bin/env python
import sqlite3
s3conn = sqlite3.connect("../DATA/presidents.db")
c = s3conn.cursor()
def row_as_dict(cursor):
'''Generate rows as dictionaries'''
column_names = [desc[0] for desc in cursor.description]
for cursor_row in cursor.fetchall():
row_dict = dict(zip(column_names, cursor_row))
yield row_dict
# select first name, last name from all presidents
num_recs = c.execute('''
select lastname, firstname
from presidents
''')
for row in row_as_dict(c):
print(row['firstname'], row['lastname'])
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python
import sqlite3
s3conn = sqlite3.connect("../DATA/presidents.db")
# uncomment to make _all_ cursors dictionary cursors
# conn.row_factory = sqlite3.Row
NAME_QUERY = '''
select firstname, lastname
from presidents
where termnum < 5
'''
cur = s3conn.cursor()
# select first name, last name from all presidents
cur.execute(NAME_QUERY)
for row in cur.fetchall():
print(row)
print('-' * 50)
dcur = s3conn.cursor() # <1>
# make _this_ cursor a dictionary cursor
dcur.row_factory = sqlite3.Row # <2>
# select first name, last name from all presidents
dcur.execute(NAME_QUERY)
for row in dcur.fetchall():
print(row['firstname'], row['lastname']) # <3>
print('-' * 50)
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python
"""
Provide metadata (tables and column names) for a Sqlite3 database
"""
import sqlite3
TABLE_QUERY = '''
select name
from sqlite_master
order by name
'''
def main(database_file):
"""
Program entry point
PARAMS:
database_file: name of Sqlite database file
"""
mycursor = connect_to_dbserver(database_file)
tables = get_all_tables_from_database(mycursor)
print('-' * 60)
for table in tables:
print(table)
columns = get_columns_for_table(mycursor, table)
for col_name, col_type, is_nullable, default_value in columns:
print(col_name, col_type, is_nullable, default_value)
def connect_to_dbserver(database_file):
"""
Connect to specified Sqlite3 database
PARAMS:
database_file: name of Sqlite3 database file to query
"""
with sqlite3.connect(database_file) as s3conn:
return s3conn.cursor()
def get_all_tables_from_database(mycursor):
"""
Get list of tables in database
PARAMS:
mycursor: open Sqlite3 database cursor
:rtype : list of table names
"""
mycursor.execute(TABLE_QUERY)
return [row[0] for row in mycursor.fetchall() if not row[0].startswith('sqlite')]
def get_columns_for_table(mycursor, table_name):
"""
Get list of columns and metadata for specified table
PARAMS:
mycursor: open Sqlite3 database cursor
table_name: table for which to return columns
CAUTION: do not pass unverified information to this function;
it is not checked for SQL injection issues
:rtype : list of lists, each with name, type, nullable flag, and default value
"""
mycursor.execute('pragma table_info({})'.format(table_name))
return [row[1:-1] for row in mycursor.fetchall()] # 1st column is ordinal; last is PK flag
if __name__ == '__main__':
main("../DATA/presidents.db")
@@ -0,0 +1,29 @@
#!/usr/bin/env python
from collections import namedtuple
import sqlite3
def named_tuple_cursor(cursor):
'''Generate rows as named tuples'''
column_names = [desc[0] for desc in cursor.description]
name_str = ' '.join(column_names)
# "row_tuple" is an arbitrary name -- any name could be used here
row_tuple = namedtuple('row_tuple', name_str)
for cursor_row in cursor.fetchall():
row_tuple = row_tuple(*cursor_row)
yield row_tuple
with sqlite3.connect("../DATA/presidents.db") as s3conn:
c = s3conn.cursor()
# select first name, last name from all presidents
num_recs = c.execute('''
select firstname, lastname
from presidents
''')
for row in named_tuple_cursor(c):
print(row.firstname, row.lastname)
@@ -0,0 +1,18 @@
#!/usr/bin/env python
import sqlite3
with sqlite3.connect("../DATA/presidents.db") as s3conn:
s3cursor = s3conn.cursor()
party_query = '''
select firstname, lastname
from presidents
where party = ?
''' # <1>
for party in 'Federalist', 'Whig':
print(party)
s3cursor.execute(party_query, (party,)) # <2>
print(s3cursor.fetchall())
print()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python
from functools import wraps
def debugger(old_func): # <1>
@wraps(old_func) # <2>
def new_func(*args, **kwargs): # <3>
print("*" * 40) # <4>
print("** function", old_func.__name__, "**") # <4>
if args: # <4>
print("\targs are ", args)
if kwargs: # <4>
print("\tkwargs are ", kwargs)
print("*" * 40) # <4>
return old_func(*args, **kwargs) # <5>
return new_func # <6>
@debugger # <7>
def hello(greeting, whom='world'):
print("{}, {}".format(greeting, whom))
hello('hello', 'world') # <8>
print()
hello('hi', 'Earth')
print()
hello('greetings')
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python
class debugger(): # <1>
function_calls = []
def __init__(self, func): # <2>
self._func = func
def __call__(self, *args, **kwargs): # <3>
# print("*" * 40) # <4>
# print("function {}()".format(self._func.__name__)) # <4>
# print("\targs are ", args) # <4>
# print("\tkwargs are ", kwargs) # <4>
#
# print("*" * 40) # <4>
self.function_calls.append( # <5>
(self._func.__name__, args, kwargs)
)
result = self._func(*args, **kwargs) # <6>
return result # <7>
@classmethod
def get_calls(cls): # <8>
return cls.function_calls
@debugger # <9>
def hello(greeting, whom="world"):
print("{}, {}".format(greeting, whom))
@debugger # <9>
def bark(bark_word, *, repeat=2):
print("{0}! ".format(bark_word) * repeat)
hello('hello', 'world') # <10>
print()
hello('hi', 'Earth')
print()
hello('greetings')
bark("woof", repeat=3)
bark("yip", repeat=4)
bark("arf")
hello('hey', 'girl')
print('-' * 60)
for i, info in enumerate(debugger.get_calls(), 1): # <11>
print("{:2d}. {:10s} {!s:20s} {!s:20s}".format(i, info[0], info[1], info[2]))
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python
#
from functools import wraps # <1>
def multiply(multiplier): # <2>
def deco(old_func): # <3>
@wraps(old_func) # <4>
def new_func(*args, **kwargs): # <5>
result = old_func(*args, **kwargs) # <6>
return result * multiplier # <7>
return new_func # <8>
return deco # <9>
@multiply(4)
def spam():
return 5
@multiply(10)
def ham():
return 8
a = spam()
b = ham()
print(a, b)
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python
def void(thing_being_decorated):
return 42 # <1>
name = "Guido"
x = void(name)
@void # <2>
def hello():
print("Hello, world")
@void
def howdy():
print("Howdy, world")
print(hello, type(hello)) # <3>
print(howdy, type(howdy)) # <3>
print(x, type(x))
+327
View File
@@ -0,0 +1,327 @@
#!/usr/bin/env python
"""
decorama -- demo of 8 combinations of decorator implementation
decorators applied to functions:
1. decorator without args @deco_func
decorator returns replacement function
2. decorator with args @deco_func(arg, ...)
decorator returns wrapper
wrapper returns replacement function
3. class without args @deco_class
__call__ IS replacement function
4. class with args @deco_class(arg, ...)
__call__ RETURNS replacement function
#TODO: straighten this mess out
decorators applied to classes:
(NOTE: replacement class is frequently the original class, but doesn't have to be)
5. decorator function without args @deco_func
decorator returns replacement class
6. decorator function with args @deco_func(arg, ...)
decorator returns wrapper
wrapper return replacement class
7. decorator class without args @deco_class
__call__ returns replacement class
8. decorator class with args @deco_class(arg, ...)
???
"""
from functools import wraps, update_wrapper
def deco_one(wrapped_function):
"""
function without params decorating a function -- the simplest kind of decorator
@deco_one
def bar():
pass
same as
bar = deco_one(bar)
:param wrapped_function: function to decorate
:return: replacement function
"""
@wraps(wrapped_function)
def _replacement(*args, **kwargs):
print("GREETINGS from deco_one!")
result = wrapped_function(*args, **kwargs)
return result + 1
return _replacement
@deco_one
def target_one():
print("Hello from target_one")
return 1
print('-' * 60)
print("** deco_one() **")
print('-' * 60)
result = target_one()
print("target_one() result is:", result)
result = target_one()
print("target_one() result is:", result)
print('-' * 60)
def deco_two(animal):
"""
function with params decorating a function
The decorator gets the args, and then returns a wrapper
function.
The wrapper gets the function being wrapped, and returns
the replacement function.
@deco_two('some string')
def bar():
pass
same as
bar = deco_two('some_string')(bar)
or,
wrapper = foo('blah')
bar = wrapper(bar)
:param value: decorator parameter
:return: wrapper function (which returns replacement function)
"""
def wrapper(wrapped_function):
@wraps(wrapped_function)
def _replacement(*args, **kwargs):
print(("GREETINGS from deco_two -- animal is {}!".format(animal)))
result = wrapped_function(*args, **kwargs)
return result
return _replacement
return wrapper
@deco_two('wombat')
def target_two_alpha():
print("GREETINGS from target_two_alpha")
@deco_two('coatimundi')
def target_two_beta():
print("GREETINGS from target_two_beta")
target_two_alpha()
target_two_alpha()
target_two_beta()
class DecoThree():
"""
class without params decorating a function
__call__() is the replacement function
__init__() is passed the wrapped function
@DecoThree
def bar():
pass
same as
bar = DecoThree(bar)
"""
def __init__(self, wrapped_function):
self.__name__ = wrapped_function.__name__
self._wrapped = wrapped_function
def __call__(self, *args, **kwargs):
print("GREETINGS from deco_three!")
result = self._wrapped(*args, **kwargs)
return result + 3
class DecoFour():
"""
class with params decorating a function
__call__() RETURNS the replacement function
@deco_four('blah')
def bar():
pass
same as
bar = deco_four('blah')(bar)
or,
wrapper = deco_four('blah')
bar = wrapper(bar)
"""
def __init__(self, value):
self._value = value
def __call__(self, wrapped_function):
@wraps(wrapped_function)
def _replacement(*args, **kwargs):
print(("GREETINGS from deco_four -- value is {}!".format(self._value)))
result = wrapped_function(*args, **kwargs)
return result + 4
return _replacement
print("Function decorators:")
@deco_one
@deco_two('APPLE')
@DecoThree
@DecoFour('BANANA')
def target_function(color, value):
"""
Target function for decorators 1-4
:param color: Color as string
:param value: Any value
:return: None
"""
print(("Hello from target_function -- color is {} and value is {}".format(color, value)))
print(("Target function's name is", target_function.__name__))
return 10 * value
TF_RESULT = target_function('red', 10)
print(("RESULT is", TF_RESULT))
print(('-' * 50))
TF_RESULT = target_function('green', 45)
print(("RESULT is", TF_RESULT))
print(('-' * 50))
print()
print()
def deco_five(target_class):
"""
function without params decorating a class
:param target_class: class to be decorated
:return: modified class
"""
print("GREETINGS from deco_five!")
@property
def _temp(self):
return self._value1
target_class.value_one = _temp
return target_class
def deco_six(fruit):
"""
function with params decorating a class; returns wrapper which is applied to target class
:param fruit:
:return: modified class
"""
print("GREETINGS from deco_six!")
def wrapper(target_class):
target_class._fruit = fruit
@property
def _temp(self):
return self._fruit
target_class.fruit = _temp
return target_class
return wrapper
@deco_five
@deco_six('MANGO')
class TargetClass():
def __init__(self, v1, v2, v3, v4):
self._value1 = v1
self._value2 = v2
self._value3 = v3
self._value4 = v4
T1 = TargetClass('fee', 'fi', 'fo', 'fum')
print(("T1 is", T1))
print(("value_one:", T1.value_one))
print(('-' * 50))
T2 = TargetClass('eeny', 'meeny', 'miny', 'mo')
print(("T2:", T2))
print(("T2.value_one:", T2.value_one))
print(("T2.fruit:", T2.fruit))
print(('-' * 50))
class DecoSeven():
"""
class without params decorating a class
__new__() returns the modified class (not __init__, because __init__ is *instance* initializer)
"""
def __new__(cls, class_): # self is the old class
print("GREETINGS from deco_seven!")
class_.color = 'blue'
return class_
@DecoSeven
class TargetClass():
pass
T1 = TargetClass()
print((T1.color))
print(("T1 id:", id(T1)))
print((TargetClass.__name__, T1))
T2 = TargetClass()
print((T2.color))
print(("T2 id:", id(T2)))
print(('-' * 50))
class DecoEight():
"""
class with params decorating a class
__call__() returns the modified class
"""
def __init__(self, color):
print("GREETINGS from deco_eight!")
self._color = color
def __call__(self, old_class):
old_class.color = self._color
return old_class
@DecoEight('purple')
class TargetClass():
pass
T1 = TargetClass()
print((T1.color))
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python
import copy
data = [
[1, 2, 3],
[4, 5, 6],
]
d1 = data # <1>
d2 = list(data) # <2>
d3 = copy.deepcopy(data) # <3>
d1.append("d1") # <4>
d1[0].append(50) # <5>
d2.append("d2") # <6>
d2[0].append(99) # <7>
d3.append("d3") # <8>
d3[0].append(500) # <9>
print("data:", data, id(data))
print("d1:", d1, id(d1))
print("d2:", d2, id(d2))
print("d3:", d3, id(d3))
print()
print("id(d1[0]):", id(d1[0]))
print("id(d2[0]):", id(d2[0]))
print("id(d3[0]):", id(d3[0]))
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python
def spam(greeting, whom='world'): # <1>
print("{}, {}".format(greeting, whom))
spam("Hello", "Mom") # <2>
spam("Hello") # <3>
print()
def ham(*, file_name, file_format='txt'): # <4>
print("Processing {} as {}".format(file_name, file_format))
ham(file_name='eggs') # <5>
ham(file_name='toast', file_format='csv')
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env python
"""
@author: jstrick
Created on Wed Mar 13 20:45:42 2013
"""
from collections import defaultdict
dd = defaultdict(lambda: 0) # <1>
dd['spam'] = 10 # <2>
dd['eggs'] = 22
print(dd['spam']) # <3>
print(dd['eggs'])
print(dd['foo']) # <4>
print('-' * 60)
fruits = ["pomegranate", "cherry", "apricot", "date", "apple",
"lemon", "kiwi", "orange", "lime", "watermelon", "guava",
"papaya", "fig", "pear", "banana", "tamarind", "persimmon",
"elderberry", "peach", "blueberry", "lychee", "grape" ]
fruit_info = defaultdict(list)
for fruit in fruits:
first_letter = fruit[0]
fruit_info[first_letter].append(fruit)
for letter, fruits in sorted(fruit_info.items()):
print(letter, fruits)
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python
animals = ['OWL', 'Badger', 'bushbaby', 'Tiger', 'Wombat', 'GORILLA', 'AARDVARK']
# {KEY: VALUE for VAR ... in ITERABLE if CONDITION}
d = {a.lower(): len(a) for a in animals} # <1>
print(d, '\n')
words = ['unicorn', 'stigmata', 'barley', 'bookkeeper']
d = {w:{c:w.count(c) for c in sorted(w)} for w in words} # <2>
for word, word_signature in d.items():
print(word, word_signature)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
default_amps = 10
default_voltage = 110
default_current = 'AC'
def amps():
return default_amps
def voltage():
return default_voltage
def current():
return default_current
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python
import smtplib
from datetime import datetime
from imghdr import what # <1>
from email.message import EmailMessage # <2>
from getpass import getpass # <3>
SMTP_SERVER = "smtp2go.com" # <4>
SMTP_PORT = 2525
SMTP_USER = 'pythonclass'
SENDER = 'jstrick@mindspring.com'
RECIPIENTS = ['jstrickler@gmail.com']
def main():
smtp_server = create_smtp_server()
now = datetime.now()
msg = create_message(
SENDER,
RECIPIENTS,
'Here is your attachment',
'Testing email attachments from python class at {}\n\n'.format(now),
)
add_text_attachment('../DATA/parrot.txt', msg)
add_image_attachment('../DATA/felix_auto.jpeg', msg)
send_message(smtp_server, msg)
def create_message(sender, recipients, subject, body):
msg = EmailMessage() # <5>
msg.set_content(body) # <6>
msg['From'] = sender
msg['To'] = recipients
msg['Subject'] = subject
return msg
def add_text_attachment(file_name, message):
with open(file_name) as file_in: # <7>
attachment_data = file_in.read()
message.add_attachment(attachment_data) # <8>
def add_image_attachment(file_name, message):
with open(file_name, 'rb') as file_in: # <9>
attachment_data = file_in.read()
image_type = what(None, h=attachment_data) # <10>
message.add_attachment(attachment_data, maintype='image', subtype=image_type) # <11>
def create_smtp_server():
password = getpass("Enter SMTP server password:") # <12>
smtpserver = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) # <13>
smtpserver.login(SMTP_USER, password) # <14>
return smtpserver
def send_message(server, message):
try:
server.send_message(message) # <15>
finally:
server.quit()
if __name__ == '__main__':
main()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python
from getpass import getpass # <1>
import smtplib # <2>
from email.message import EmailMessage # <3>
from datetime import datetime
TIMESTAMP = datetime.now().ctime() # <4>
SENDER = 'jstrick@mindspring.com'
RECIPIENTS = ['jstrickler@gmail.com']
MESSAGE_SUBJECT = 'Python SMTP example'
MESSAGE_BODY = """
Hello at {}.
Testing email from Python
""".format(TIMESTAMP)
SMTP_USER = 'pythonclass'
SMTP_PASSWORD = getpass("Enter SMTP server password:") # <5>
smtpserver = smtplib.SMTP("smtp2go.com", 2525) # <6>
smtpserver.login(SMTP_USER, SMTP_PASSWORD) # <7>
msg = EmailMessage() # <8>
msg.set_content(MESSAGE_BODY) # <9>
msg['Subject'] = MESSAGE_SUBJECT # <10>
msg['from'] = SENDER # <11>
msg['to'] = RECIPIENTS # <12>
try:
smtpserver.send_message(msg) # <13>
except smtplib.SMTPException as err:
print("Unable to send mail:", err)
finally:
smtpserver.quit() # <14>
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env python
import os
os.system("hostname") # <1>
with os.popen('netstat -an') as netstat_in: # <2>
for entry in netstat_in: # <3>
if 'ESTAB' in entry: # <4>
print(entry, end='')
print()
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python
import sys
if sys.version_info.major == 3 and sys.version_info.minor >= 6:
name = "Tim"
count = 5
avg = 3.456
info = 2093
result = 38293892
print(f"Name is [{name:<10s}]") # <1>
print(f"Name is [{name:>10s}]") # <2>
print(f"count is {count:03d} avg is {avg:.2f}") # <3>
print(f"info is {info} {info:d} {info:o} {info:x}") # <4>
print(f"${result:,d}") # <5>
city = 'Orlando'
temp = 85
print(f"It is {temp} in {city}") # <6>
else:
print("Sorry -- f-strings are only supported by Python 3.6+")
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import sys
import os
if len(sys.argv) < 2:
start_dir = "."
else:
start_dir = sys.argv[1]
for base_name in os.listdir(start_dir): # <1>
file_name = os.path.join(start_dir, base_name)
if os.access(file_name, os.W_OK): # <2>
print(file_name, "is writable")
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python
import fileinput
for line in fileinput.input(): # <1>
if 'bird' in line:
print('{}: {}'.format(fileinput.filename(), line), end=' ') # <2>
+20
View File
@@ -0,0 +1,20 @@
from datetime import date
from dateutil.relativedelta import relativedelta # <.>
def first_last_days(year):
first_last_pairs = []
for month in range(1,13):
first_day = date(year, month, 1)
last_day = first_day + relativedelta(day=1, months=1, days=-1) # <.>
first_last_pairs.append((first_day, last_day)) # <.>
return first_last_pairs
if __name__ == '__main__':
pairs = first_last_days(2020)
for first, last in pairs:
fwd = first.strftime("%A") # <.>
lwd = last.strftime("%A") # <.>
print("{} {:9s} {} {:9s}".format(first, fwd, last, lwd))
print()
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python
def say_hello(): # <1>
print("Hello, world")
print()
# <2>
say_hello() # <3>
def get_hello():
return "Hello, world" # <4>
h = get_hello() # <5>
print(h)
print()
def sqrt(num): # <6>
return num ** .5
m = sqrt(1234) # <7>
n = sqrt(2)
print("m is {:.3f} n is {:.3f}".format(m, n))
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python
def fun_one(): # <1>
print("Hello, world")
print("fun_one():", end=' ')
fun_one()
print()
def fun_two(n): # <2>
return n ** 2
x = fun_two(5)
print("fun_two(5) is {}\n".format(x))
def fun_three(count=3): # <3>
for _ in range(count):
print("spam", end=' ')
print()
fun_three()
fun_three(10)
print()
def fun_four(n, *opt): # <4>
print("fun_four():")
print("n is ", n)
print("opt is", opt)
print('-' * 20)
fun_four('apple')
fun_four('apple', "blueberry", "peach", "cherry")
def fun_five(*, spam=0, eggs=0): # <5>
print("fun_five():")
print("spam is:", spam)
print("eggs is:", eggs)
print()
fun_five(spam=1, eggs=2)
fun_five(eggs=2, spam=2)
fun_five(spam=1)
fun_five(eggs=2)
fun_five()
def fun_six(**named_args): # <6>
print("fun_six():")
for name in named_args:
print(name, "==> ", named_args[name])
fun_six(name="Lancelot", quest="Grail", color="red")
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python
# sum the squares of a list of numbers
# using list comprehension, entire list is stored in memory
s1 = sum([x * x for x in range(10)]) # <1>
# only one square is in memory at a time with generator expression
s2 = sum(x * x for x in range(10)) # <2>
print(s1, s2)
print()
page = open("../DATA/mary.txt")
m = max(len(line) for line in page) # <3>
page.close()
print(m)
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env python
import sys
import os.path
if sys.platform == 'win32':
user_key = 'USERNAME'
else:
user_key = 'USER'
count_key = 'COUNT'
os.environ[count_key] = "42" # <1>
print("count is", os.environ[count_key], "user is", os.environ[user_key]) # <2>
print("count is", os.environ.get(count_key), "user is", os.environ.get(user_key)) # <3>
user = os.getenv(user_key) # <4>
count = os.getenv(count_key)
print("count is", count, "user is", user)
cmd = "count is ${} user is ${}".format(count_key, user_key)
print("cmd:", cmd)
print(os.path.expandvars(cmd)) # <5>
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env python
from glob import glob
files = glob('../DATA/*.txt') # <1>
print(files, '\n')
no_files = glob('../JUNK/*.avi')
print(no_files, '\n')
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python
from pprint import pprint # <1>
spam = 42 # <2>
ham = 'Smithfield'
def eggs(fruit): # <3>
name = 'Lancelot' # <4>
idiom = 'swashbuckling' # <4>
print("Globals:")
pprint(globals()) # <5>
print()
print("Locals:")
pprint(locals()) # <6>
eggs('mango')
@@ -0,0 +1,6 @@
#!/usr/bin/env python
import electrical as e # <1>
import navigation as n # <2>
print(e.current()) # <3>
print(n.current()) # <4>
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python
from animal import Animal
class Insect(Animal):
'''
An animal with 2 sets of wings and 3 pairs of legs
'''
def __init__(self, species, name, sound, can_fly=True): # <1>
super().__init__(species, name, sound) # <2>
self._can_fly = can_fly
@property
def can_fly(self): # <3>
return self._can_fly
if __name__ == '__main__':
mon = Insect('monarch butterfly', 'Mary', None) # <4>
scar = Insect('scarab beetle', 'Rupert', 'Bzzz', False)
for insect in mon, scar:
flying_status = 'can' if insect.can_fly else "can't"
print("Hi! I am {} the {} and I {} fly!".format( # <5>
insect.name, insect.species, flying_status
),
)
insect.make_sound() # <6>
print()
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import inspect
class Spam: # <1>
pass
def ham(p1, p2='a', *p3, p4, p5='b', **p6): # <2>
print(p1, p2, p3, p4, p5, p6)
for thing in (inspect, Spam, ham):
print("{}: Module? {}. Function? {}. Class? {}".format(
thing.__name__,
inspect.ismodule(thing), # <3>
inspect.isfunction(thing), # <4>
inspect.isclass(thing), # <5>
))
print()
print("Function spec for Ham:", inspect.getfullargspec(ham)) # <6>
print()
print("Current frame:", inspect.getframeinfo(inspect.currentframe())) # <7>
@@ -0,0 +1,43 @@
#!/usr/bin/env python
#
import json
from datetime import date
class Parrot(): # <1>
def __init__(self, name, color):
self._name = name
self._color = color
@property
def name(self): # <2>
return self._name
@property
def color(self):
return self._color
parrots = [ # <3>
Parrot('Polly', 'green'), #
Parrot('Peggy', 'blue'),
Parrot('Roger', 'red'),
]
def encode(obj): # <4>
if isinstance(obj, date): # <5>
return obj.ctime() # <6>
elif isinstance(obj, Parrot): # <7>
return {'name': obj.name, 'color': obj.color} # <8>
return obj # <9>
data = { # <10>
'spam': [1, 2, 3],
'ham': ('a', 'b', 'c'),
'toast': date(2014, 8, 1),
'parrots': parrots,
}
print(json.dumps(data, default=encode, indent=4)) # <11>
@@ -0,0 +1,58 @@
#!/usr/bin/env python
#
import json
from datetime import date, datetime
from functools import singledispatch
# uncomment if Python version < 3.4 and comment out above line
# from singledispatch import singledispatch
class Parrot():
def __init__(self, name, color):
self._name = name
self._color = color
@property
def name(self):
return self._name
@property
def color(self):
return self._color
parrots = [
Parrot('Polly', 'green'),
Parrot('Peggy', 'blue'),
Parrot('Roger', 'red'),
]
data = {
'spam': [1, 2, 3],
'ham': ('a', 'b', 'c'),
'date': date(2014, 8, 1),
'timestamp': datetime(2014, 8, 1, 15, 34, 19),
'parrots': parrots,
}
@singledispatch
def encode(obj):
return obj
@encode.register(date)
def encode_date(date_obj):
return date_obj.isoformat()
@encode.register(Parrot)
def encode_parrot(parrot_obj):
return {'name': parrot_obj.name, 'color': parrot_obj.color}
# register other encoding functions here
print(json.dumps(data, default=encode, indent=4))
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python
import json
with open('../DATA/solar.json') as solar_in: # <1>
solar = json.load(solar_in) # <2>
# json.loads(STRING)
# json.load(FILE_OBJECT)
# print(solar)
print(solar['innerplanets']) # <3>
print('*' * 60)
print(solar['innerplanets'][0]['name'])
print('*' * 60)
for planet in solar['innerplanets'] + solar['outerplanets']:
print(planet['name'])
print("*" * 60)
for group in solar:
if group.endswith('planets'):
for planet in solar[group]:
print(planet['name'])
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python
import json
george = [
{
'num': 1,
'lname': 'Washington',
'fname': 'George',
'dstart': [1789, 4, 30],
'dend': [1797, 3, 4],
'birthplace': 'Westmoreland County',
'birthstate': 'Virginia',
'dbirth': [1732, 2, 22],
'ddeath': [1799, 12, 14],
'assassinated': False,
'party': None,
},
{
'spam': 'ham',
'eggs': [1.2, 2.3, 3.4],
'toast': {'a': 5, 'm': 9, 'c': 4},
}
] # <1>
js = json.dumps(george, indent=4) # <2>
print(js)
with open('george.json', 'w') as george_out: # <3>
json.dump(george, george_out, indent=4) # <4>
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python
class Knight():
def __init__(self, name, title, color):
self._name = name
self._title = title
self._color = color
@property # <1>
def name(self): # <2>
return self._name
@property
def color(self):
return self._color
@color.setter # <3>
def color(self, color):
self._color = color
@property
def title(self):
return self._title
if __name__ == '__main__':
k = Knight("Lancelot", "Sir", 'blue')
# Bridgekeeper's question
print('Sir {}, what is your...favorite color?'.format(k.name)) # <4>
# Knight's answer
print("red, no -- {}!".format(k.color))
k.color = 'red' # <5>
print("color is now:", k.color)
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env python
fruits = ['watermelon', 'Apple', 'Mango', 'KIWI', 'apricot', 'LEMON', 'guava']
sfruits = sorted(fruits, key=lambda e: e.lower()) # <1>
print(" ".join(sfruits))
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env python
def trimmed(file_name):
with open(file_name) as file_in:
for line in file_in:
yield line.rstrip('\n\r') # <1>
for trimmed_line in trimmed('../DATA/mary.txt'): # <2>
print(trimmed_line)
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python
fruits = ['watermelon', 'apple', 'mango', 'kiwi', 'apricot', 'lemon', 'guava']
values = [2, 42, 18, 92, "boom", ['a', 'b', 'c']]
ufruits = [fruit.upper() for fruit in fruits] # <1>
afruits = [fruit for fruit in fruits if fruit.startswith('a')] # <2>
doubles = [v * 2 for v in values] # <3>
print("ufruits:", " ".join(ufruits))
print("afruits:", " ".join(afruits))
print("doubles:", end=' ')
for d in doubles:
print(d, end=' ')
print()
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env python
import sys
import logging
import logging.handlers
logger = logging.getLogger('ThisApplication') # <1>
logger.setLevel(logging.DEBUG) # <2>
if sys.platform == 'win32':
eventlog_handler = logging.handlers.NTEventLogHandler("Python Log Test") # <3>
logger.addHandler(eventlog_handler) # <4>
else:
syslog_handler = logging.handlers.SysLogHandler() # <5>
logger.addHandler(syslog_handler) # <6>
# note -- use your own SMTP server...
email_handler = logging.handlers.SMTPHandler(
('smtpcorp.com', 8025),
'LOGGER@pythonclass.com',
['jstrick@mindspring.com'],
'ThisApplication Log Entry',
('jstrickpython', 'python(monty)'),
) # <7>
logger.addHandler(email_handler) # <8>
logger.debug('this is debug') # <9>
logger.critical('this is critical') # <9>
logger.warning('this is a warning') # <9>
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import logging
logging.basicConfig( # <1>
filename='../TEMP/exception.log',
level=logging.WARNING, # <2>
)
for i in range(3):
try:
result = i/0
except ZeroDivisionError:
logging.exception('Logging with exception info') # <3>
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import logging
logging.basicConfig(
format='%(name)s %(asctime)s %(levelname)s %(message)s', # <1>
filename='../TEMP/formatted.log',
level=logging.INFO,
)
logging.info("this is information")
logging.warning("this is a warning")
logging.info("this is information")
logging.critical("this is critical")
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
import logging
logging.basicConfig(
filename='../TEMP/simple.log',
level=logging.WARNING,
) # <1>
logging.warning('This is a warning') # <2>
logging.debug('This message is for debugging') # <3>
logging.error('This is an ERROR') # <4>
logging.critical('This is ***CRITICAL***') # <5>
logging.info('The capital of North Dakota is Bismark') # <6>
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python
colors = ['red', 'green', 'blue', 'purple', 'pink', 'yellow', 'black'] # <1>
for color in colors: # <2>
print(color)
print()
with open('../DATA/mary.txt') as mary_in: # <3>
for line in mary_in: # <4>
print(line, end='') # <5>
print()
while True: # <6>
name = input("What is your name? ") # <7>
if name.lower() == 'q':
break # <8>
print("Welcome,", name)
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python
from animal import Animal
class Mammal(Animal): # <1>
def __init__(self, species, name, sound, gestation):
super(Mammal, self).__init__(species, name, sound)
self._gestation = gestation
@property
def gestation(self): # <2>
"""Length of gestation period in days"""
return self._gestation
if __name__ == "__main__":
mammal1 = Mammal("African lion", "Bob", "Roarrrr", 120)
print(mammal1.name, "is a", mammal1.species, "--", end=' ')
mammal1.make_sound()
print("Number of animals", mammal1.zoo_size())
mammal2 = Mammal("Fruit bat", "Freddie", "Squeak!!", 180)
print(mammal2.name, "is a", mammal2.species, "--", end=' ')
mammal2.make_sound()
print("Number of animals", mammal2.zoo_size())
print("Number of animals", Mammal.zoo_size())
mammal1.kill()
print("Number of animals", Mammal.zoo_size())
print("Gestation period of the", mammal1.species, "is", mammal1.gestation, "days")
print("Gestation period of the", mammal2.species, "is", mammal2.gestation, "days")
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python
import os
import psutil
class MemoryChecker():
"""
Callable class to get current memory use of program.
Instances of this class may be called, at which time
they will return current memory use.
"""
def __init__(self):
self.process = psutil.Process(os.getpid()) # <1>
def __call__(self):
return self.process.memory_info().rss # <2>
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
class Spam(): # <1>
def __init__(self, name):
self._name = name
def eggs(self): # <2>
print("Good morning, {}. Here are your delicious fried eggs.".format(self._name, ))
s = Spam('Mrs. Higgenbotham') # <3>
s.eggs() # <4>
def scrambled(self): # <5>
print("Hello, {}. Enjoy your scrambled eggs".format(self._name, ))
setattr(Spam, "eggs", scrambled) # <6>
s.eggs() # <7>
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python
class Meta(type):
def __prepare__(class_name, bases):
"""
"Prepare" the new class. Here you can update the base classes.
:param name: Name of new class as a string
:param bases: Tuple of base classes
:return: Dictionary that initializes the namespace for the new class (must be a dict)
"""
print("in metaclass (class={}) __prepare__()".format(class_name), end=' ==> ')
print("params: name={}, bases={}".format(class_name, bases))
return {'animal': 'wombat', 'id': 100}
def __new__(metatype, name, bases, attrs):
"""
Create the new class. Called after __prepare__(). Note this is only called when classes
:param metatype: The metaclass itself
:param name: The name of the class being created
:param bases: bases of class being created (may be empty)
:param attrs: Initial attributes of the class being created
:return:
"""
print("in metaclass (class={}) __new__()".format(name), end=' ==> ')
print("params: type={} name={} bases={} attrs={}".format(metatype, name, bases, attrs))
return super().__new__(metatype, name, bases, attrs)
def __init__(cls, *args):
"""
:param cls: The class being created (compare with 'self' in normal class)
:param args: Any arguments to the class
"""
print("in metaclass (class={}) __init__()".format(cls.__name__), end=' ==> ')
print("params: cls={}, args={}".format(cls, args))
super().__init__(cls)
def __call__(self, *args, **kwargs):
"""
Function called when the metaclass is called, as in NewClass = Meta(...)
:param args:
:param args:
:param kwargs:
:return:
"""
print("in metaclass (class={})__call__()".format(self.__name__))
class MyBase():
pass
print('=' * 60)
class A(MyBase, metaclass=Meta):
id = 5
def __init__(self):
print("In class A __init__()")
print('=' * 60)
class B(MyBase, metaclass=Meta):
animal = 'wombat'
def __init__(self):
print("In class B __init__()")
print('-' * 60)
m1 = A()
print('-' * 60)
m2 = B()
print('-' * 60)
m3 = A()
print('-' * 60)
m4 = B()
print('-' * 60)
print("animal: {} id: {}".format(A.animal, B.id))
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python
class Singleton(type): # <1>
_instances = {} # <2>
def __new__(typ, *junk):
# print("__new__()")
return super().__new__(typ, *junk)
def __call__(cls, *args, **kwargs): # <3>
# print("__call__()")
if cls not in cls._instances: # <4>
cls._instances[cls] = super().__call__(*args, **kwargs) # <5>
return cls._instances[cls] # <6>
class ThingA(metaclass=Singleton): # <7>
def __init__(self, value):
self.value = value
class ThingB(metaclass=Singleton): # <7>
def __init__(self, value):
self.value = value
ta1 = ThingA(1) # <8>
ta2 = ThingA(2)
ta3 = ThingA(3)
tb1 = ThingB(4)
tb2 = ThingB(5)
tb3 = ThingB(6)
for thing in ta1, ta2, ta3, tb1, tb2, tb3:
print(type(thing).__name__, id(thing), thing.value) # <9>
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python
import re
from pymongo import MongoClient, errors
FIELD_NAMES = (
'termnumber lastname firstname '
'birthdate '
'deathdate birthplace birthstate '
'termstartdate '
'termenddate '
'party'
).split() # <1>
mc = MongoClient() # <2>
try:
mc.drop_database("presidents") # <3>
except errors.PyMongoError as err:
print(err)
db = mc["presidents"] # <4>
coll = db.presidents # <5>
with open('../DATA/presidents.txt') as presidents_in: # <6>
for line in presidents_in:
flds = line[:-1].split(':')
kvpairs = zip(FIELD_NAMES, flds)
record_dict = dict(kvpairs)
coll.insert_one(record_dict) # <7>
print(db.list_collection_names()) # <8>
print()
abe = coll.find_one({'termnumber': '16'}) # <9>
print(abe, '\n')
for field in FIELD_NAMES:
print("{0:15s} {1}".format(field.upper(), abe[field])) # <10>
print('-' * 50)
for president in coll.find(): # <11>
print("{0[firstname]:25s} {0[lastname]:30s}".format(president))
print('-' * 50)
rx_lastname = re.compile('^roo', re.IGNORECASE)
for president in coll.find({'lastname': rx_lastname}): # <12>
print("{0[firstname]:25s} {0[lastname]:30s}".format(president))
print('-' * 50)
for president in coll.find({"birthstate": 'Virginia'}): # <13>
print("{0[firstname]:25s} {0[lastname]:30s}".format(president))
print('-' * 50)
print("removing Millard Fillmore")
result = coll.delete_one({'lastname': 'Fillmore'}) # <14>
print(result)
result = coll.delete_one({'lastname': 'Roosevelt'}) # <14>
print(result)
print('-' * 50)
result = coll.delete_one({'lastname': 'Bush'})
print(dir(result))
print()
result = coll.count_documents({}) # <15>
print(result)
for president in coll.find(): # <11>
print("{0[firstname]:25s} {0[lastname]:30s}".format(president))
print('-' * 50)
animals = db.animals
print(animals, '\n')
animals.insert_one({'name': 'wombat', 'country': 'Australia'})
animals.insert_one({'name': 'ocelot', 'country': 'Mexico'})
animals.insert_one({'name': 'honey badger', 'country': 'Iran'})
for doc in animals.find():
print(doc['name'])
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python
import sys
import random
from multiprocessing import Manager, Lock, Process, Queue, freeze_support
from queue import Empty
import time
NUM_ITEMS = 25000 # <1>
POOL_SIZE = 100
class RandomWord(): # <2>
def __init__(self):
with open('../DATA/words.txt') as words_in:
self._words = [word.rstrip('\n\r') for word in words_in]
self._num_words = len(self._words)
def __call__(self): # <3>
return self._words[random.randrange(0, self._num_words)]
class Worker(Process): # <4>
def __init__(self, name, queue, lock, result): # <5>
Process.__init__(self)
self.queue = queue
self.result = result
self.lock = lock
self.name = name
def run(self): # <6>
while True:
try:
word = self.queue.get(block=False) # <7>
word = word.upper() # <8>
with self.lock:
self.result.append(word) # <9>
except Empty: # <10>
break
if __name__ == '__main__':
if sys.platform == 'win32':
freeze_support()
word_queue = Queue() # <11>
manager = Manager() # <12>
shared_result = manager.list() # <13>
result_lock = Lock() # <14>
random_word = RandomWord() # <15>
for i in range(NUM_ITEMS):
w = random_word()
word_queue.put(w) # <16>
start_time = time.ctime()
pool = [] # <17>
for i in range(POOL_SIZE): # <18>
worker_name = "Worker {:03d}".format(i)
w = Worker(worker_name, word_queue, result_lock, shared_result) # <19>
#
w.start() # <20>
pool.append(w) # <21>
for t in pool:
t.join() # <22>
end_time = time.ctime()
print((shared_result[-50:])) # <23>
print(len(shared_result))
print(start_time)
print(end_time)
@@ -0,0 +1,39 @@
#!/usr/bin/env python
class AnimalBase(): # <1>
def __init__(self, name):
self._name = name
def get_id(self):
print(self._name)
class CanBark(): # <2>
def bark(self):
print("woof-woof")
class CanFly(): # <2>
def fly(self):
print("I'm flying")
class Dog(CanBark, AnimalBase): # <3>
pass
class Sparrow(CanFly, AnimalBase): # <3>
pass
d = Dog('Dennis')
d.get_id() # <4>
d.bark() # <5>
print()
s = Sparrow('Steve')
s.get_id()
s.fly() # <6>
print()
print("Sparrow mro:", Sparrow.mro())
@@ -0,0 +1,5 @@
#!/usr/bin/env python
print("Loading my_package")
# __all__ = ['module_a', 'module_b']
# from my_package import module_a, module_b
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# (c) 2017 John Strickler
#
def function_a():
print("Hello from function_a")
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# (c) 2017 John Strickler
#
def function_b():
print("Hello from function_b")
@@ -0,0 +1,5 @@
#!/usr/bin/env python
# (c) 2017 John Strickler
#
def function_c():
print("Hello from function_c")
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python
"""
@author: jstrick
Created on Thu Mar 14 09:07:57 2013
"""
from collections import namedtuple
Knight = namedtuple('Knight', 'name title color quest comment') # <1>
k = Knight('Bob', 'Sir', 'green', 'whirled peas', 'Who am i?') # <2>
print(k.title, k.name) # <3>
print(k[1], k[0]) # <4>
print()
knights = {} # <5>
with open('../DATA/knights.txt') as knights_in:
for line in knights_in:
flds = line.rstrip().split(':')
knights[flds[0]] = Knight(*flds) # <6>
for knight, info in knights.items(): # <7>
print('{0} {1}: {2}'.format(info.title, knight, info.color))

Some files were not shown because too many files have changed in this diff Show More