• dynamic typing
  • monkey patching: dynamic replacement of attributes at runtime, classes are mutable
  • complex scoping rules
  • complex deployment due to incomptible libs

string operations

yorkie = 'Marlowe'
mutt = 'Kafka'
 
ylen = len(yorkie) #length of variable yorkie
print(ylen) #prints 7
print(len(yorkie)) #does the same thing
len(yorkie) #also does the same thing, print is implicit
print(yorkie.lower()) #lower cases the string
print(yorkie.strip('aeiou')) #removes vowels from end of string
print(mutt.split('f')) #splits "Kafka" into ['Ka', 'ka']
print(mutt.count('a')) #prints 2, the number of a's in string
yorkie.replace('a','4')  #replace a's with 4's

Dictionaries

colorvalues = {'red' : 1, 'blue' : 2, 'green' : 3, 'yellow' : 4, 'orange' : 5}
colorvalues #prints {'blue': 2, 'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}
colorvalues['blue'] #prints 2
colorvalues.keys() #retrieves all keys as a list:
                   #['blue', 'orange', 'green', 'yellow', 'red']
colorvalues.pop('blue') #prints 2 and removes the blue key/value pair
colorvalues #after pop, we have:
            #{'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}

Lists

groceries = ['ham','spam','eggs']
len(groceries) #returns 3
print groceries[1] #prints spam
 
for x in groceries:
    print x.upper() #prints HAM SPAM EGGS
 
groceries[2] = 'bacon'
groceries #list is now ['ham','spam','bacon']
 
groceries.append('eggs')
groceries #list is now ['ham', 'spam', 'bacon', 'eggs']
 
groceries.sort()
groceries #list is now ['bacon', 'eggs', 'ham', 'spam']

file read:

def printSmiles():
  text = open("file.txt", "w").readlines()
  for line in text:
    print line

directory files listing

listing files in a directory

from os import listdir
 
for f in listdir('.'):
    print('Processing {} file...'.format(f))

important libs:

  • os - provides OS independent functionality, like working with paths and reading/writing files.
  • subprocess - to spawn new processes and interact with their input/output streams and return codes. You can use this to launch programs already installed on your system, but note that this might not be the best option if you’re worried about the portablity of your script.
  • shutil - offers high-level operations on files and collections of files.
  • argparse - parsing command-line arguments and building command-line interfaces

Reading STDIN

cat names.txt | namecount_py

namecount_py:

#!/usr/bin/env python3
import sys
 
def count_names():
    names = {}
    for name in sys.stdin.readlines():
        name = name.strip()
 
        if name in names:
            names[name] += 1
        else:
            names[name] = 1
 
    for name, count in names.items():
        sys.stdout.write("{0}\t{1}\n".format(name, count))
 
if __name__ == "__main__":
    count_names()

Scripting

#!/usr/bin/python
 
import os
from time import strftime
 
stamp = strftime("%Y-%m-%d %H:%M:%S")
logfile = '/path/to/your/logfile.log'
path = '/path/to/tmp/directory/'
 
files = os.listdir(path)
bytes = 0
numfiles = 0
 
for f in files:
    if f.startswith('sess_'):
        info = os.stat(path + f)
        numfiles += 1
        bytes += info[6]
 
 
if numfiles > 1:
    title = 'files'
else:
    title = 'file'
 
 
string = stamp + " -- " + str(numfiles) + " session " \
+ title +", " + str(bytes) + " bytes\n"
 
file = open(logfile,"a")
file.writelines(string)
file.close()

basic program:

#! /usr/bin/env python
 
def smile( ):
   print("Smile!", end="")
 
for i in range(3,0,-1):
   for j in range(i):
      smile()
   print("")

CSV

pip install csvkit
<code>
 
 
==== JSON ====
<code python>
import json
data = json.loads('{ "foo": 1, "bar": [10, "apples"] }')
sample = { "blue": [1,2], "ocean": "water" }
json_string = json.dumps(sample)

simplest webserveer

to transfer files across newtwork computers

python -m SimpleHTTPServer

resources

  • py2exe: converte script in un eseguibile standalone

criticism

  • instance variables made private by prefixing the names with underscores
  • instance methods are defined with “self” as the first argument, which is hokey enough as it is, but “self” is not passed in at the actual method invocation, which is weirdly inconsistent and thus confusing
  • not all attributes you would expect to find in an object are there – len() is a case in point – it exists as a global function
  • under the hood, Python is purely object-oriented, but you can bypass all of this and use Python strictly procedurally, which is oddly schizophrenic
  • GIL on multithreding
  • confusing withespacing