Raspi_Python_Notes
Random Notes
Use \ to continue long lines.
Timer:
from time import sleep
sleep(0.5) # sleep for a half second
Or,
import time
print "start: %s" % time.ctime()
time.sleep(2.5) # sleep 2.5 sec
print "end: %s" % time.ctime()
LineFeeds
To print without a linefeed, there are a couple of options:
import sys
sys.stdout.write(myvar)
Or, can also use:
PYTHON2: print "abc", << Adding a column will cause the text or var to be printed without a newline, but will include a space.
PYTHON3: print("abc",end="")
or even:
print("abc",end="",flush=true) << causes buffer to be flushed immediately.
To REMOVE a linefeed from a string (same as "chomp" in perl) - use "rstrip"
a="this is a line with a linefeed\n"
a.rstrip('\n')
a.rstrip() << removes RIGHT hand, all whitespace characters on the end of the line.
a.strip() << removes whitespace on both LEFT and RIGHT *ends* of the lines, but not spaces in the middle.
a.lstrip() << removes any whitespace on the LEFT of the line.
String Operations
import string
To uppercase a string:
x.upper()
To lowercase a string:
x.lower()
List Operations
See:
len(x)
list.sort()
list.reverse()
list.append("next_entry")
list.insert(....) << find info for this one...
list.remove('bad_element')
RegEx
To parse and extract a value from a string:
import re
regex = re.compile(r":AVA" r"(?P<pnum>(\d+))" r"(?P<pval>(\d+))")
found=regex.search(buf)
if found == None:
print "Invalid return statement\n"
else:
print "Port number: " + pnum + "Port value: " + pval
SYSTEM CALLS
import subprocess
a=subprocess.check_output("ls", "-ald")
To get return code:
a=subprocess.call("ls", "-al > tmp_file")
print "return code: " + a
# output is in file tmp_file
*** not sure if this will work - not sure if each arg is separate, or all together...
Serial Port Communications (with Raspi)
import serial
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=3)
ser.flushInput() # flushes input buffer
ser.write("Hello World\n")
c = ser.read() # Note - this only reads ONE character.