Python quick start guide

As I bought Raspberry PI I needed to learn some basics of Python. What is so special about Python is that it doesn't use so many parenthesis. Instead it is very important the indentation of the code.

Save the scripts with .py suffix.

Run scripts with $ python myScript.py

Hello world

Example of printouts

#!/usr/bin/python

print "Hello World"

count = 100
miles = 1.8
name = "John"
# comment

print count
print miles
print name

Lists

Creating list of objects

#!/usr/bin/python

list = [ 'aaa', 123, 22.3, "bla bla" ]
print list[0]
print list[1]
print list[2]
print list[3]
print list[1:3]
print list[2:]

Maps

Map of objects (key-value pairs)

#!/usr/bin/python

map = {}
map['one'] = "This is one"
map[2] = "This is two"
print map['one']

mapp = { 'name':'john', 'code':1234 }
print mapp['name']
print mapp
print mapp.keys()
print mapp.values()

Conditions

Basic if-else example

#!/usr/bin/python

x = 101

if (x == 100):
    print "x=100 - True"
else:
    print "False"

Loops

Example of while and for loops

#!/usr/bin/python

count = 0
while (count < 5):
print 'Count: ', count
count += 1
else:
print count, " is more than 5"

for letter in 'Python':
print 'Current letter: ', letter

fruits = [ 'apple', 'banana', 'mango' ]
for fruit in fruits:
print 'Fruit: ', fruit

for index in range(len(fruits)):
print 'Fruit[', index, ']: ', fruits[index]

Read input arguments

When the script is invoked with additional arguments (like $ python myScript.py arg1 arg2)

#!/usr/bin/python

import sys

print "Number of arguments: ", len(sys.argv)
print "Argument list: ", str(sys.argv)

Read user input

Some user intarcations

#!/usr/bin/python

x = 1
while x == 1:
    num = raw_input("Enter number: ")
    print "You entered: ", num

Show time

Show current timestamp

#!/usr/bin/python

import time

ticks = time.time()
print "ticks since 1970: ", ticks

localtime = time.localtime(time.time())
print 'current time: ', localtime

Prime numbers

Print prime numbers

#!/usr/bin/python

for num in range(1,200000):
    for i in range(2,num):
        if num%i == 0:
            j=num/i
            # print '%d equals %d * %d' % (num, i, j)
            break
    else:
        print num, ' is prime number'

Read file

Example how to read file

#!/usr/bin/python

f = open("test.txt", "r+")
str = f.read();
print "File name: ", f.name
print "Read: ", str
f.close()

Write file

Example how to write data to file

#!/usr/bin/python

import os

print os.getcwd()

# read file
f = open("test.txt", "r+")
str = f.read();
print "File name: ", f.name
print "Read: ", str
f.close()

# write to file
f = open("test.txt", "wb")
f.write("Python is great")
f.close

Creating custom modules

First create a module and define some functions

#!/usr/bin/python

def sum(a, b):
    return a+b

Then create a script that imports your module

#!/usr/bin/python

import mylib

x = mylib.sum(1, 2)
print "sum=", x

Creating classes

Create a class Monkey

#!/usr/bin/python

class Monkey:

    count = 0

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Monkey.count += 1

    def displayCount(self):
        print "Number of monkeys: %d" % Monkey.count

    def displayMonkey(self):
        print "Name: ", self.name, ", Age: ", self.age

Then import your class and use it:

#!/usr/bin/python

import MonkeyLib

m1 = MonkeyLib.Monkey("Mark", 2)
m2 = MonkeyLib.Monkey("Fred", 5)

m1.displayMonkey()
m2.displayMonkey()
print "Number of monkeys: ", MonkeyLib.Monkey.count


Another example of Employee class (all in one py file)

#!/usr/bin/python

class Employee:

    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1

    def displayCount(self):
        print "Number of employees: %d" % Employee.empCount

    def displayEmployee(self):
        print "Name: ", self.name, ", Salary: ", self.salary


emp1 = Employee("John", 2000)
emp2 = Employee("Lucy", 3500)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total number of employees: ", Employee.empCount
print "---------------------------"

print "-- set attributes--"
emp1.age = 20;
#print "emp1.age=", emp1.age
#del emp1.age # delete attribute


if (hasattr(emp1, 'age') == False):
    setattr(emp1, 'age', 28)
    print "attribute age set: ", emp1.age
else:
    print "get attribute age: ", getattr(emp1, 'age')

delattr(emp1, 'age')

Insert measurement into InfluxDB with Python

To insert a measurement into InfluxDB in Python, you need to write a http client that sends POST request to InfluxDB HTTP API.

Here is piece of python code that initiates http connection with the InfluxDB server, prepares POST request and prints returned HTTP error code.

Remark: InfluxDB returns error code 204 if measurement was successfully inserted.

#!/usr/bin/env python

import httplib

httpServ = httplib.HTTPConnection("192.168.1.115", 8086)
httpServ.connect()

stringValue = str(22)
httpServ.request('POST', '/write?db=myDatabase', 'temperature,sensor=T1 value=' + stringValue)

response = httpServ.getresponse()
print response.status

httpServ.close()