Python Cheat Sheet

Author: Brian Nettles | Date Created: June 1, 2018 | Visits: 174

One important thing that I learned while going through the training process of mastering the Google Cloud Platform was just how important Python Scripting was to the subject. Python is a powerful language that is perfect for writing not only startup scripts but also for establishing redeployable and scalable processes. While you can do practically any programming task in Python, my focus is on administration of the cloud. Python truly does make a difference in automating processes.

I have put together this cheat sheet together for everyone who needs a quick reference on commonly used commands done in Python. All examples are tested using Python 3.

I highly recommend the book Automate the Boring Stuff with Python written by Al Sweigart. These examples did not come directly from this book; however, many of the examples were inspired by its contents.

Console Input with If Statement

print("Enter your first name")
firstName = input()
print('Welcome ' + firstName)
print("Enter your password")
password=input()
if password=='mypassword':
    print("Successfull Authentication")
else:
    print("Wrong password")

Twenty Random Numbers between 1 and 10

import random

for i in range(20): 
  print( str(i+1) + '. ' + str(random.randint(1, 10)))

Working with Files and Directories

import os, shutil

print(os.getcwd())

os.chdir('/Users/mydirectoryname/development/python')
print(os.getcwd())

os.chdir('/Users/mydirectoryname/development/python/learning')
print(os.getcwd())

pathpythonmade='/Users/mydirectoryname/development/python/learning/pythonmade'
if not os.path.exists(pathpythonmade):
  os.makedirs('/Users/mydirectoryname/development/python/learning/pythonmade')
os.chdir('/Users/mydirectoryname/development/python/learning/pythonmade')
print(os.getcwd())

os.chdir('/Users/mydirectoryname/development/python/learning')
print(os.getcwd())

print(os.path.abspath("."))
print(os.path.abspath("pythonmade"))
print(os.path.isabs("."))
print(os.path.isabs(os.path.abspath(".")))

path='/Users/mydirectoryname/development/python/learning/regex.py'
print(os.path.basename(path))
print(os.path.dirname(path))
print(path.split(os.path.sep))
print(os.path.getsize(path))
path2='/Users/mydirectoryname/development/python/learning'
print(os.listdir(path2))
print(os.path.exists(path2))

for filename in os.listdir(path2):
    if os.path.isfile(filename):
        print(os.path.getsize(filename))

csvfile = '/Users/mydirectoryname/development/python/learning/gsod1929.csv'
gsod1929file = open(csvfile)
gsod1929Content = gsod1929file.readlines()
copyFile = open('gsod1929copy.csv', 'w')  #w creates a new file  #a appends


for line in gsod1929Content:
    print(line)
    copyFile.write(line)

copyFile.close()
gsod1929file.close()

shutil.copy("gsod1929copy.csv", "./pythonmade")
shutil.copytree("./pythonmade", "./pythonmade3")
shutil.move("./gsod1929copy.csv", "./pythonmade2/")
shutil.move("./pythonmade2/gsod1929copy.csv", "./")
shutil.move("./gsod1929copy.csv", "./pythonmade2/gsod1929copy_new.csv")
shutil.move("./pythonmade2/gsod1929copy_new.csv", "./gsod1929copy.csv")
os.unlink("path_with_filename")  #delete files
os.rmdir("directoryname_or_path") #must by empty
shutil.rmtree("directoryname_or_path") # delete directory

#traverse the tree
for foldername, subfolders, filenames in os.walk('/Users/mydirectoryname/development/java'):
    for subfolder in subfolders:
        print('subfolder ' + subfolder)
    for filename in filenames:
        print('folder and file ' + foldername + '/' + filename)

Persist Data with Shelve

import shelve

shelfFile = shelve.open('mydata')
friends=['Dan','Jeremy','Bill']
shelfFile['friends'] = friends
shelfFile.close()

newShelfFile=shelve.open('mydata')
print(newShelfFile['friends'])
newShelfFile.close()

Create / Extract Zip File

import zipfile, os, shutil

foldernametozip='trisummit-old'
os.chdir("/Users/mydirectory/development/python")
zipname= foldernametozip+'.zip'

backup=zipfile.ZipFile(zipname, 'w')
for foldername, subfolders, filenames in os.walk(foldernametozip):
  print('adding files in folder %s' %(foldername))
  backup.write(foldername)
  for filename in filenames:
    if filename.endswith('.zip'):
        continue
    backup.write(os.path.join(foldername, filename))

# Zip file created called trisummit-old.zip and in contains all the files.
shutil.move("./trisummit-old.zip", "./trisummit-old-renamed.zip")
toextract = zipfile.ZipFile('trisummit-old-renamed.zip','r')
toextract.extractall('trisummit-old-renamed')
toextract.close()

Exception Handling

repetitions=5
try:
    if repetitions>4:
        raise Exception('Too many repetitions. Reduce the size.')
except Exception as err:
    print('We hit exception. ' + str(err))
    
print('Program finished.')

Output:
We hit exception. Too many repetitions. Reduce the size.
Program finished.

Logging

import logging

logging.basicConfig(filename="debugging.log", level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of Program')

repetitions=5
#assert repetitions==4
try:
    if repetitions>4:
        raise Exception('Too many repetitions. Reduce the size')
except Exception as err:
    logging.error('We hit exception ' + str(err))

logging.debug('Program finished')

Download File from Web

You may have to install "requests" by invoking the command "pip3 install requests" from the command line.
import requests

res = requests.get('https://storage.googleapis.com/rockiestocumorahserver.appspot.com/audiobooks/JesusTheCrist/JesusTheChristChapter10.mp3')
try:
    res.raise_for_status()
    mp3file=open('JesusTheChristChapter10.mp3','wb')
    for chunk in res.iter_content(100000):
        mp3file.write(chunk)
    mp3file.close()
except Exception as exc:
    print('Exception at get %s' %(exc))

Use Console Output for Data

This script was created to delete the many docker images I wanted deleted. The docker command returned all the values with a lot more information which needed to be parsed out and stored as an array. Then I was able to loop through the array for the delete commands.
import subprocess

cmd = subprocess.Popen("docker image ls -a".split(), stdout=subprocess.PIPE)
cmd_out, cmd_err = cmd.communicate()
outputs = cmd_out.decode('utf-8').split('\n')
toDelete =[]
lineItem=0
for output in outputs:
  if lineItem>0:
    toDelete.append(output[44:56])
  lineItem=lineItem+1

#toDelete is defined and populated.  Now loop it and delete each item.
for item in toDelete:
  cmd = "docker image rm " + item
  try:
    subprocess.check_call(cmd.split(), stdout=subprocess.PIPE)
  except Exception as err:
    print('We hit exception. ' + str(err))

 
Trisummit Technologies
6421 N. Lena Place
Tucson, AZ 85741
575-322-6697
© 2018 All Rights Reserved