воскресенье, 27 мая 2012 г.

command line options

There is useful foo in C which can parse command line options. Just like when user writes
user#pc: ls -la
Here is the detail description:

In Python there is just the same foo:

And one more useful link with tips and tricks for Python:
http://www2-pcmdi.llnl.gov/cdat/tips_and_tricks/python_tips/index_html



#!/usr/bin/python
import getopt
import sys
import multiprocessing
import threading
import time
multi_line_help = """
Usage: args.py [OPTIONS]
args.py is an example of command line parameters usage
options:
-h --help\tprints this help
-p --process\tstarts N process and prints \
 \"hello from proc\" from each one
-t --threads\tstarts N threads and prints \
 \"hello from thread\" from each one"""


def printMultilineHelp():
print multi_line_help

def printHelp():
print "Usage: args.py [OPTIONS]"
print "args.py is an example of command line parameters usage"
print "options:"
print "-h --help", "\t", "prints this help"
print "-p --process", "\t", "starts N process and prints \ \"hello from proc\" from each one"
print "-t --threads", "\t", "starts N threads and prints \ \"hello from thread\" from each one"

def processCall():
p = multiprocessing.current_process()
print "hello from process:", p.name, "id:", p.pid
while True:
time.sleep(1)

def threadCall():
t = threading.currentThread()
print "hello from thread:", t.getName()


options, remainder = getopt.getopt(sys.argv[1:], 'hp:t:',
["help", "process=", "threads="])
            
num_threads = 0
num_process = 0
# if you need to handle exact one option in time, use switch
# or use one function to handle and than sys.exit()
            
if options == []:
printMultilineHelp()
sys.exit()
            
for opt, arg in options:
print "options:", opt, "arguments", arg
if opt in ("-h", "--help"):
printHelp()
sys.exit()
elif opt in ("-p", "--process"):
num_process = int(arg)
print 'Start', num_process, 'process'
elif opt in ("-t", "--threads"):
num_threads = int(arg)
print 'Start', num_threads, 'thread'

process_jobs = []
threads_jobs = []
if num_process != 0:
p = multiprocessing.current_process()
print "Caller process name:", p.name, "id:", p.pid
for i in range(num_process):
j = multiprocessing.Process(target=processCall, \
      name = 'process_' + str(i))
# use if you don't want to wait  
  # for completion and do another stuff
j.daemon = True
process_jobs.append(j)
j.start()
#j.join()
print process_jobs[:]


if num_threads != 0:
for i in range(num_threads):
j = threading.Thread(name = "thread_" + str(i), \
      target = threadCall)
# use if you don't want to wait 
  # for completion and do another stuff
#j.daemon = True
threads_jobs.append(j)
j.start()
j.join()
print threads_jobs[:]

# now when parrent stops, all childs stops too
#while True:
# time.sleep(1)


Based on:
http://www.doughellmann.com/PyMOTW/contents.html

вторник, 1 мая 2012 г.

python serial usage

Do the UART connection with board or pc with serial module.


import serial
import array
l = [0x1, 0x2, 0x3]
t = array.array('B', l)
s = t.tostring()
ser = serial.Serial(0,115200) 
#ser = serial.Serial('/dev/ttyS0', 115200)
ser.write(s)
r = ser.read(5)
ser.close()
m = memoryview(r)
rl = m.tolist()
print rl

It is the simplest way...

четверг, 12 апреля 2012 г.

python ctypes usage

With python ctypes arrays, bytes pointers etc. can be scripted. 
In python 2.7 ctypes can be used like this:


from ctypes import *
def crc16(data, numBytes):
crc16 = c_uint16(0)
crc16l = c_uint8(0xFF)
crc16h = c_uint8(0xFF)
symbol = c_uint8()
for counter in range(numBytes):
symbol = c_uint8(data[counter])
symbol.vaule ^= crc16h.value
symbol.value ^= (symbol.value >> 4)
crc16h.value = crc16l.value ^ (symbol.value << 4) ^
                 symbol.value >> 3) 
crc16l.value = symbol.value ^ (symbol.value << 5)
crc16.value |= crc16l.value
crc16.value <<= 8
crc16.value |= crc16h.value
return crc16
if __name__ == '__main__':
data = (c_uint8 * 5)()
data[0] = 0
data[1] = 1
data[2] = 2
data[3] = 3
data[4] = 4
print hex(crc16(data, data.__len__()).value)


Main thing with xor and shift is x.value, without it error appears:
symbol ^= crc16h.value
TypeError: unsupported operand type(s) for ^=: 'c_ubyte' and 'int'