Python

= Basics=

Variables
Declaring Variables: list=[1,2,3] string="Hello" int=23

Basic argument specifiers:

%s                     - String (or any object with a string representation, like numbers) %d                     - Integers %f                     - Floating point numbers %. f  - Floating point numbers with a fixed amount of digits to the right of the dot. %x/%X                  - Integers in hex representation (lowercase/uppercase)

Indentation is Mandatory in python:

num=12 if num>5: print("Number is greater than 5") if num<20: print("Number is lesser than 20") print("Program Ended")

Operator Precedence from highest to lowest order:



Statements
IF & ELIF statements:

num=9 if num==5: print("Number is 5") elif num ==11: print("Number is 11") elif num==7: print("Number is 7") else: print("Number isn't 5,11,7")

AND returns true only if both are true >>> 1 == 1 and 2==2 True >>> 1 == 1 and 2==3 False >>> 1 != 1 and 2==2 False >>> 1 == 1 and 2==2 True

OR returns true if either of both arguments are true; false if both are false. >>> 1 != 1 or 2==2 True >>> 1 == 1 or 2==2 True >>> 1 == 1 or 2==3 True

Lists
words=["Hello","World","!"] print(words[0]) print(words[1]) print(words[2])

Mixed List: number=3 things=['string',0,[1,2,number],4,56] print(things[1]) print(things[2]) print(things[2][2])

List Operators: nums = [1,2,3] print(nums+[4,5,6]) print(nums*3)

in operator: >>> words=['spam',"egg"] >>> print("spam" in words) True >>> print("tomato" in words) False >>> print (not "tomato" in words) True >>> print ("tomato" not in words) True

Append to the list: nums=[1,2,3] nums.append(4) print(nums)

Len function:

nums=[1,3,5,2,4] print(len(nums))
 * 1) Unlike append, len is a normal function rather than a method.
 * 2) Therefore it is written before the list it is being called on, without a dot.

Insert Method is similar to append, but allows to add at any position in the list words=["Python","fun"] index=1 words.insert(index,"is") print(words)

Loops
While Loop runs more than once, till condition is true, once condition is false, next section of code is executed: i=1 while i<=500: print(i) i=i+1

print("Finished !")

Infinity while loop: condition always remain True: while 1==1: print('In a loop..!!')

Break the infinity Loop: i=0 while 1==1: print(i) i=i+1 if i>=25: print('Breaking!') break

print("Finished!")

Continue this jumps back to top of the loop, rather than stopping it i=0 while True: i=i+1 if i==10: print('Skip 10') continue if i==25: print("Breaking") break print(i) print("Finished!")

words = ["hello","world","spam","egg"] counter = 0 max_index = len(words)-1
 * While Loop

while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1

words = ["hello","world","spam","egg"] for word in words: print(word + "!")
 * Same code can be created using FOR Loop but fewer lines

Loop can be combined with Range objects(No need to call List on range objects in For Loop as it is not indexed): for i in range(5): print("hello")

Functions
def myfunc: print("spam") print("spam") print("spam")

myfunc

Arguments

def printe(word): print(word + "!")

printe("spam") printe("world") printe("egg")

= Running Unix Commands =

os.system(deprecated)
import os os.system("date")

import os f = os.popen('date') now = f.read print "Today is ", now

Subprocess
Basic usage: import subprocess subprocess.call("command1") subprocess.call(["command1", "arg1", "arg2"])

Execute the date command: import subprocess subprocess.call("date")

Execute ls command with arguments: import subprocess subprocess.call(["ls", "-l", "/etc/resolv.conf"])

Execute date command: import subprocess p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate print "Today is", output

import subprocess p = subprocess.Popen(["ls", "-l", "/etc/resolv.conf"], stdout=subprocess.PIPE) output, err = p.communicate print "*** Running ls -l command ***\n", output

import subprocess p = subprocess.Popen(["ping", "-c", "10", "4.2.2.2"], stdout=subprocess.PIPE) output, err = p.communicate print output

The only problem with above code is that output, err = p.communicate will block next statement till ping is completed i.e. you will not get real time output from the ping command.

So you can use the following code to get real time output: import subprocess cmdping = "ping -c4 4.2.2.2" p = subprocess.Popen(cmdping, shell=True, stderr=subprocess.PIPE) while True: out = p.stderr.read(1) if out == '' and p.poll != None: break if out != '': sys.stdout.write(out) sys.stdout.flush

=Using SSH=

import paramiko ssh = paramiko.SSHClient ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) ssh.connect( '192.168.1.23', username = 'root', password = 'libreelec' ) stdin, stdout, stderr = ssh.exec_command( 'ls -al' )

for line in stdout: print('... ' + line.strip('\n')) ssh.close

= Using Databases =

Installing Modules for MySQL: sudo apt-get install python-pip python-dev libmysqlclient-dev pip install MySQL-python

Connecting to a DB on localhost(need to create a db 'testdb' beforehand): import MySQLdb db = MySQLdb.connect("localhost","guest","guest123","testdb")
 * 1) !/usr/bin/python

cursor = db.cursor cursor.execute("SELECT VERSION") data = cursor.fetchone print "Database Version : %s " % data db.close

Creating Database:

import MySQLdb db = MySQLdb.connect("localhost","guest","guest123","testdb")
 * 1) !/usr/bin/python

cursor = db.cursor sql="""CREATE table book_tbl (      book_id INT NOT NULL AUTO_INCREMENT,       book_title VARCHAR(100) NOT NULL,       book_author VARCHAR(100) NOT NULL,       submission_date DATE,       PRIMARY KEY( book_id ));"""

cursor.execute(sql) db.close

= GUI =

Hello World
from Tkinter import Tk, Label

root = Tk

w = Label(root, text="Hello World!") w.pack

root.mainloop


 * References