python
command line
run python file
python3 [file]
configure the path
export PYTHONPATH="$PWD:/path/to/additional/modules"
python3 [file]
don't create .pyc files
export PYTHONDONTWRITEBYTECODE=1
basic types
boolean
boolean literals
True
False
strings
trim / strip
line.strip()
string is blank
line.strip() == ""
length of string
len(line)
string starts with
line.startswith("http")
substring
line[3:len(line)]
replace substring occurrences
original.replace([find], [replacement])
original.replace([find], [replacement], [max])
splitting a string on a literal separator of one or more characters
variable.split('.')
universal to string method
str(object)
check if a string is empty / blank
if value:
print("string is not empty")
if value.strip():
print("string is not blank")
joining elements of an iterable into a string
separator = "\n"
separator.join(myiterable)
escape url characters
import urllib.parse
escaped = urllib.parse.quote(string)
format'Hello {0}!'.format('world')
"This month is {f}!".format(f='February')
"This month is {m}. It has {d} days.".format(m=month, d=days)
tutorial
https://dzone.com/articles/python-string-format-examples
numbers
convert to int
int(float('14.3'))
int('15')
arrays
stack = []
stack.append('value')
for value in stack:
print(value)
array length
len(stack)
filter elements
filtered = filter(lambda number: number % 2 == 0, numbers)
filtered = [number for number in numbers if number % 2 == 0]
list comprehension
generated = [2 * n for n in range(50)]
sort an array (or any other iterable)
sorted(myarray)
sorted(myarray, reverse=True)
sets
create a set
empty = set()
fruits = {'apple', 'banana', 'pear'}
from_array = set([1,2,3])
add an element
empty.add('element')
count elements
len(thisset)
get a sorted list of keys
sorted(mydict.keys())
documentation
https://www.w3schools.com/python/python_sets.asp
dictionaries
creating a dictionary
mydict = {}
mydict = { "a" : 1 }
mydict = { "a" : 1, "b" : 2 }
getting a value for a key
x = mydict['key']
x = mydict.get('key')
getting a value for a key with default
x = mydict.get('key', 'default')
setting a value
mydict['key'] = 'value'
checking if a key exists
if "key" in mydict:
print("key exists")
iterating keys
for key in mydict:
print(key)
iterating values
for value in mydict.values():
print(value)
iterating keys and values
for key, value in mydict.items():
print(key + ":" + value)
list keys sorted
sorted(mydict.keys())
creating a copy
dict([variable])
documentation
https://www.w3schools.com/python/python_dictionaries.asp
tuples
creating a tuple
mytuple = ("string value", 1)
accessing a tuple
unwrap = mytuple[1]
control flow
logical operators
x == y
x != y
x > y
x < y
x >= y
x <= y
if statements
if [test]:
[statement]
elif [test]:
[statement]
else:
[statement]
ternary operator
result = [if_value] if [condition] else [else_value]
for each loop
for element in iterable:
print(element)
for loop with fixed iterations
for i in range(10):
print(i)
functions
define a function
def [name]( [parameters] ):
"docstring"
print("todo: code goes here")
optional parameter
def optional(param="default"):
print(param)
workaround for complex types (musn't be shared)
def append_to(complex=None):
if complex is None:
complex = []
main method
if __name__ == "__main__":
print("hello world!")
define a lambda function
multiply = lambda a,b : a*b
map elements from a list using a (lambda) function
list(map(lambda v: v+1, [1,2]))
map elements from multiple lists
list(map(lambda a,b: a+b, ["a","b"], ["1","2"]))
exception handling
throw an exception
raise Exception('This user appears unequipped to use this application!')
configuring a logger manually
import logging
log = logging.getLogger()
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
printing a log statement
log = logging.getLogger()
log.debug ('format with parameter %s', 'some value')
log.info ('format with parameter %s', 'some value')
log.warning ('format with parameter %s', 'some value')
log.error ('format with parameter %s', 'some value')
log.critical ('format with parameter %s', 'some value')
documentation
https://docs.python.org/3/library/logging.html
classes
get the type of a variable
print(type(dict))
defining a simple class
class [name]:
"""class description"""
static_variable = [value]
def __init__(self):
"""constructor"""
self.instance_variable = [value]
def [method]([args]):
return [result]
create instance
instance = [name]()
defining an instance variable
class [name]:
def __init__(self, value):
self.instance_variable = value
instance = [name]([value])
calling referring to methods / variables
class [name]:
def __init__(self):
myvar = "value"
def a(self):
print(self.myvar)
def b(self):
self.a()
input / output
arguments
print without newline
print(line, end="")
command line arguments
import sys
for arg in sys.argv:
print(arg)
get command line argument by index
first = sys.argv[1]
count command line arguments
count = len(sys.argv)
piped input
echo -e "a\nb" | python -c '
import sys
for line in sys.stdin:
sys.stdout.write(line)
'
environment variables
get home directory
os.getenv("HOME")
processes
calling a shell process
import subprocess
subprocess.Popen(['/path/to/script.sh'])
calling a shell process and passing in environment variables
import os
import subprocess
variables=dict(os.environ, APPLE='PEAR')
subprocess.Popen(['/usr/bin/env'], env=variables)
files
concatenate file paths
os.path.join([path]...)
verify directory
import os.path
if not os.path.exists('work'):
if not os.path.isfile('work'):
if not os.path.isdir('work'):
create directory
import os
if not os.path.isdir(directory):
os.mkdir(directory)
list directory (direct children)
os.listdir("/tmp")
list directory contents (nested children)
from os import walk
for (dirpath, dirnames, filenames) in walk(mypath):
print(filenames)
read file
file = open('workfile', 'r')
contents = file.read()
print(contents)
read lines
file = open('workfile', 'r')
for line in file:
print(line, end='')
write file
file = open('workfile', 'w')
file.write('This is a test\n')
copy file
import shutil
shutil.copyfile([from], [to])
glob files by extension
for file in glob.glob("*.txt"):
print(file)
csv
parse csv file
with open([path], 'r') as lines:
iterator = csv.reader(lines, delimiter=',')
next(iterator) # skip header
for row in iterator:
for(cell in row):
print(cell)
specify delimiter
csv.reader(lines, delimiter=',')
documentation
https://docs.python.org/3/library/csv.html
threads
sleep
import time
time.sleep(10)
one liners
call python with script as argument
python -c 'print("hello world")'
use piped input
echo "hello world" | python -c "import sys; print(sys.stdin.read())"
use piped input line for line
echo -e "a b\r\nc d" | python3 -c 'import sys; [print(line, end="") for line in sys.stdin]'
testing
a simple test case
#!/usr/bin/python3
import unittest
class TestSomething(unittest.TestCase):
def test_passes(self):
self.assertEqual(1, 1)
def test_fails(self):
self.assertEqual(0, 1)
if __name__ == '__main__':
unittest.main()
assertions
assertTrue(x, msg?) # is True
assertFalse(x, msg?) # is False
assertEqual(a, b, msg?) # a == b
assertNotEqual(a, b, msg?) # a != b
assertIs(a, b, msg?) # a is b
assertIsNone(x, msg?) # is None
assertIn(a, b, msg?) # a in b
assertIsInstance(a, b, msg?) # isInstance(a,b)
...
documentation
tutorial
https://realpython.com/python-testing/#writing-your-first-test
API
https://docs.python.org/3/library/unittest.html