Difference between revisions of "Python"
(→Libraries) |
m (→For) |
||
(45 intermediate revisions by the same user not shown) | |||
Line 41: | Line 41: | ||
==For== | ==For== | ||
− | for i in range(127,-1,-1): #step from 127 to 0 by 1 | + | for i in range(2, 10 + 1, 1): #step from 2 to 10 by 1 |
+ | print i | ||
+ | |||
+ | for i in range(127, 0 - 1, -1): #step from 127 to 0 by 1 | ||
print i | print i | ||
Line 77: | Line 80: | ||
=Math= | =Math= | ||
+ | ==Arithmetic functions== | ||
a = b + 2 #addition | a = b + 2 #addition | ||
a = b - 2 #subtraction | a = b - 2 #subtraction | ||
Line 82: | Line 86: | ||
a = b / 2 #division | a = b / 2 #division | ||
a = b % 2 #modulo division (divides b by 2, and returns the remainder) | 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= | =Bitwise functions= | ||
Line 90: | Line 101: | ||
a = a ^ 2 #sets a to all the bits in b logical XORed 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) | 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= | =Files= | ||
Line 96: | Line 109: | ||
outputfile1.write("Hello\r\n") #\r\n creates a new line, so whatever is written next will be on a new line | outputfile1.write("Hello\r\n") #\r\n creates a new line, so whatever is written next will be on a new line | ||
outputfile1.close() | outputfile1.close() | ||
+ | |||
+ | ==Read a text file, line by line== | ||
+ | f1 = open('file.txt','r') | ||
+ | for line in f1: | ||
+ | print line | ||
+ | f1.close() | ||
+ | |||
+ | ==Reading a binary file into an array== | ||
+ | with open(filename.bin, mode='rb') as f1: | ||
+ | chrarray = f1.read() | ||
+ | f1.close() | ||
+ | |||
+ | for c in chrarray: | ||
+ | bytevalue = ord(c) #convert from a character to an int value (of the character) | ||
+ | #do something | ||
+ | |||
+ | ==Writing to a binary file== | ||
+ | with open(filename, mode='b') as f1: #change b to ab for append (add data to the end of an existing file) mode | ||
+ | f1.write(struct.pack('I', 123456789)) #write value as unsigned int ('I') instead of string | ||
+ | f1.close() | ||
+ | to see a full list of types, please check [https://docs.python.org/2/library/struct.html this link]<br /> | ||
+ | For example, you can f1.write(struct.pack('<Q', 0x50D822A1E911F43E)) #< for little-endian, 'Q' is 8 byte unsigned long long | ||
+ | |||
+ | ==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 | ||
+ | |||
+ | ==Delete a file== | ||
+ | import os | ||
+ | |||
+ | os.remove("file.txt") | ||
+ | |||
+ | ==Check if a character is in a file== | ||
+ | if '.' in open('ipaddr.txt').read(): | ||
+ | #do something | ||
=Strings= | =Strings= | ||
==Combining strings== | ==Combining strings== | ||
print "abc" + "123" | 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<br /> | ||
+ | H<br /> | ||
+ | e<br /> | ||
+ | l<br /> | ||
+ | l<br /> | ||
+ | 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 | ||
+ | |||
+ | ==Check if a string is a digit== | ||
+ | "5".isdigit() | ||
+ | Some examples<br /> | ||
+ | print "1".isdigit()<br /> | ||
+ | True<br /> | ||
+ | |||
+ | print "01".isdigit()<br /> | ||
+ | True<br /> | ||
+ | |||
+ | print "0.1".isdigit()<br /> | ||
+ | False<br /> | ||
+ | |||
+ | print "-1".isdigit()<br /> | ||
+ | False<br /> | ||
+ | |||
+ | print "20".isdigit()<br /> | ||
+ | True<br /> | ||
+ | |||
+ | print "2v".isdigit()<br /> | ||
+ | False | ||
+ | |||
+ | ==Convert a value to a string== | ||
+ | voltage = 20 | ||
+ | print str(voltage) + " Volts" | ||
+ | This will print 20 Volts | ||
+ | |||
+ | ==Convert a string to an integer value== | ||
+ | day = "05" | ||
+ | tomorrow = int(day) + 1 # the conversion from int to string is done here | ||
+ | print "tomorrow will be the " + str(tomorrow) + "th" | ||
+ | This will produce: tomorrow will be the 6th | ||
+ | |||
+ | ==Convert a string to an float value== | ||
+ | print 2 * float("3.14159") | ||
+ | This will output 6.28318 | ||
+ | |||
+ | ==Remove all whitespaces (spaces, tabs etc) from the front and end of a string== | ||
+ | print " Hello ".strip() | ||
+ | This becomes "Hello" | ||
+ | |||
+ | ==Get the length of a string== | ||
+ | print len("Hello") | ||
+ | This will output 5 | ||
+ | |||
+ | =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 | ||
+ | import struct | ||
+ | import fcntl | ||
+ | |||
+ | 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("<nowiki>http://ip.jsontest.com/</nowiki>").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 | ||
+ | |||
+ | ==Send UDP packets== | ||
+ | import socket | ||
+ | |||
+ | UDP_IP = socket.gethostbyname('myawesomeserver.org') #get IP address to send the UDP packets to | ||
+ | UDP_PORT = 8080 | ||
+ | |||
+ | sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #Internet UDP | ||
+ | |||
+ | sock.sendto("Hello", (IP, port)) | ||
+ | |||
+ | =Raspberry PI specific= | ||
+ | ==GPIO== | ||
+ | import RPi.GPIO as GPIO | ||
+ | |||
+ | GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme | ||
+ | GPIO.setup(4, GPIO.OUT) #set pin as output | ||
+ | |||
+ | GPIO.output(4, GPIO.HIGH) #set the pin high | ||
+ | |||
+ | ==Serial== | ||
+ | import serial | ||
+ | |||
+ | ser = serial.Serial() | ||
+ | ser.baudrate = 9600 | ||
+ | ser.port = '/dev/serial0' #COM1 (or other number) in windows | ||
+ | ser.timeout=2 | ||
+ | |||
+ | ser.open() | ||
+ | |||
+ | while True: | ||
+ | serstring = ser.readline() | ||
[[Category:Computing]] | [[Category:Computing]] |
Latest revision as of 14:49, 2 October 2017
Contents
- 1 Application
- 2 Loops
- 3 Conditionals
- 4 Math
- 5 Bitwise functions
- 6 Files
- 7 Strings
- 7.1 Combining strings
- 7.2 Splitting strings (by a character)
- 7.3 Stepping though the characters in a string
- 7.4 Slicing
- 7.5 Check if a string is a digit
- 7.6 Convert a value to a string
- 7.7 Convert a string to an integer value
- 7.8 Convert a string to an float value
- 7.9 Remove all whitespaces (spaces, tabs etc) from the front and end of a string
- 7.10 Get the length of a string
- 8 Time
- 9 Network
- 10 Raspberry PI specific
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(2, 10 + 1, 1): #step from 2 to 10 by 1 print i
for i in range(127, 0 - 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()
Read a text file, line by line
f1 = open('file.txt','r') for line in f1: print line f1.close()
Reading a binary file into an array
with open(filename.bin, mode='rb') as f1: chrarray = f1.read() f1.close() for c in chrarray: bytevalue = ord(c) #convert from a character to an int value (of the character) #do something
Writing to a binary file
with open(filename, mode='b') as f1: #change b to ab for append (add data to the end of an existing file) mode f1.write(struct.pack('I', 123456789)) #write value as unsigned int ('I') instead of string f1.close()
to see a full list of types, please check this link
For example, you can f1.write(struct.pack('<Q', 0x50D822A1E911F43E)) #< for little-endian, 'Q' is 8 byte unsigned long long
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
Delete a file
import os os.remove("file.txt")
Check if a character is in a file
if '.' in open('ipaddr.txt').read(): #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
Check if a string is a digit
"5".isdigit()
Some examples
print "1".isdigit()
True
print "01".isdigit()
True
print "0.1".isdigit()
False
print "-1".isdigit()
False
print "20".isdigit()
True
print "2v".isdigit()
False
Convert a value to a string
voltage = 20 print str(voltage) + " Volts"
This will print 20 Volts
Convert a string to an integer value
day = "05" tomorrow = int(day) + 1 # the conversion from int to string is done here print "tomorrow will be the " + str(tomorrow) + "th"
This will produce: tomorrow will be the 6th
Convert a string to an float value
print 2 * float("3.14159")
This will output 6.28318
Remove all whitespaces (spaces, tabs etc) from the front and end of a string
print " Hello ".strip()
This becomes "Hello"
Get the length of a string
print len("Hello")
This will output 5
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 import struct import fcntl 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
Send UDP packets
import socket UDP_IP = socket.gethostbyname('myawesomeserver.org') #get IP address to send the UDP packets to UDP_PORT = 8080 sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #Internet UDP sock.sendto("Hello", (IP, port))
Raspberry PI specific
GPIO
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme GPIO.setup(4, GPIO.OUT) #set pin as output GPIO.output(4, GPIO.HIGH) #set the pin high
Serial
import serial ser = serial.Serial() ser.baudrate = 9600 ser.port = '/dev/serial0' #COM1 (or other number) in windows ser.timeout=2 ser.open() while True: serstring = ser.readline()