Python
Contents
Application
File Header
#!/usr/bin/python
Comments
These begin with the # character
Libraries
these go under the file header and in the format of
import libraryname
or
from libraryname import sublibraryname
Subroutines
These must be placed at the top, under the file header and library includes
def functionname(value): #do something return somevariable
Variables
There is no method to define a variable type, it is determined by the type of the first value it gets set to
a = 42 will create an int called a with value 42
Loops
Infinite
while True: #code to loop
While (check then run)
a = 0 while a < 10: a += 1
While (run then check)
while True: #code if i == 10: break #this exits the while loop
For
for i in range(127,-1,-1): #step from 127 to 0 by 1 print i
Conditionals
Equal
if i == 10: print i
Not equal
if i != 10: print i
Greater than
if i > 10: print i
Less than
if i < 10: print i
Greater than or equal to
if i >= 10: print i
Less than or equal to
if i <= 10: print i
If Else
if i == 10: print i else: print "I isn't 10"
Math
Arithmetic functions
a = b + 2 #addition a = b - 2 #subtraction a = b * 2 #multiplication a = b / 2 #division a = b % 2 #modulo division (divides b by 2, and returns the remainder)
If the name of the variable you are setting is the same as the first parameter variable name (example: a = a + 1), then it can also be written as a += 1
Generating random values
import random print random.randint(1, 5) #prints a random whole number between 1 and 5
Bitwise functions
a = b >> 2 #shift the bits of an int right by an amount of times (2 in this case) a = b << 2 #shift the bits of an int left by an amount of times (2 in this case) a = b | 2 #sets a to all the bits in b logical ORed with all the bits in 2 a = b & 2 #sets a to all the bits in b logical ANDed with all the bits in 2 a = a ^ 2 #sets a to all the bits in b logical XORed with all the bits in 2 a = ~ b #sets a to all the bits in b switched (0s become 1, 1s become 0)
If the name of the variable you are setting is the same as the first parameter variable name (example: a = a << 1), then it can also be written as a <<= 1
Files
Writing to a text file
with open("filename.txt", "w") as outputfile1: #w for write, change to a for append to add to the bottom of an existing file outputfile1.write("Hello\r\n") #\r\n creates a new line, so whatever is written next will be on a new line outputfile1.close()
Check if a file exists
import os if os.path.exists('/var/somefile.txt') == True: #note, in windows the slashes go the other way and may contain drive letters #do something
Strings
Combining strings
print "abc" + "123"
Splitting strings (by a character)
mystring = "Hello,World" paramlist = mystring.split(',') #paramlist will then contain an array of 2 separate strings, ['Hello', 'World']. paramlist[0] will contain Hello and paramlist[1] will contain World and paramlist[0][1] contains e
Stepping though the characters in a string
mystring = "Hello" for c in mystring: print c:
This will produce
H
e
l
l
o
Slicing
Get a specific character from a position within a string
mystring = "Hello" print mystring[1] #this will print the 2nd character (e) 0 is the first
Get a subsection of a string
mystring = "Hello" printmystring[1:3+1] #this will start at character position 1 and end at character position 3
This will produce ell
Get the start of a string
mystring = "Hello" print mystring[:2] #this will give you 2 characters from the string, beginning at the start (0)
This will produce He
Get the end of a string
mystring = "Hello" print mystring[2:] #this will start at character position 2, until the end of the string
This will produce llo
Get the last n characters of a string
mystring = "Hello" print mystring[-2:] #this will get the last 2 characters from the string
This will produce lo
Get all except the last n characters
mystring = "Hello" print mystring[:-2] #this will get all characters in the string, except the last 2
This will produce Hel
Time
Adding a delay
import time time.sleep(1) #delay 1 second time.sleep(0.1) #delay 0.1 seconds (100ms)
Get the current date and time
from datetime import datetime now = datetime.now() print now.strftime("%d/%m/%Y %I:%M:%S.%f %p")
an example of its output: 02/10/2017 11:53:34.803179 PM
Network
Check if connected to the internet
import socket def is_connected(): try: socket.create_connection(("www.google.com", 80)) except: return False else: return True
Check if a network interface is up (Linux only)
import os def is_interface_up(interface): #interface as string, returns True/False with open('/sys/class/net/'+interface+'/operstate') as f1: line=f1.readline() f1.close() statusSTR=str.strip(line) #remove new line whitespace if statusSTR=="up": #ifconfil will output inet addr:x.x.x.x or unspec addr:[NONE SET] #os.system("/sbin/ifconfig "+interface+" | grep \"inet \">ipaddr.txt") #get the ip4 address, sbin added incase path not yet set. removed, deprecated os.system("/sbin/ip -4 addr | grep inet | grep " + interface + " | awk -F\" \" '{print $2}' | sed -e 's/\/.*$//'>" + scriptpath + "/ipaddr.txt") #get the ip4 address, sbin added incase path not yet set if '.' in open(scriptpath + '/ipaddr.txt').read(): #check if ip address or nothing retval=True time.sleep(1) #network intermitantly fully up before this point else: retval=False os.remove(scriptpath + '/ipaddr.txt') else: retval=False return retval
Get the local IP address of a specific interface (Linux only)
import socket def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])
Get the external Internet WAN IP address of your network
import urllib, json def get_external_ip(): ipdata = json.loads(urllib.urlopen("http://ip.jsontest.com/").read()) return ipdata["ip"]
Receive UDP packets
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Internet UDP sock.bind(("192.168.0.2", 8080)) #the ip address of the interface you want to listen on, the port you want to listen on while True: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes #data will contain the data bytes, addr will contain the (external) IP address it came from #code here