= Python = Python is a programming language that lets you work more quickly and integrate your systems more effectively. Links: * [[http://docs.python.org/2/library/]] * [[http://www.tutorialspoint.com/python/]] == UTF-8 == At the start of source code files: {{{#!highlight python # -*- coding: utf-8 -*- print u"Olá mundo" # hello world in portuguese }}} Letter '''á''' is encoded as hexadecimal '''0xC3A1''' in UTF-8 and as '''0x00E1''' in UTF-16. [[http://www.fileformat.info/info/unicode/char/e1/index.htm]] Letter '''ú''' is encoded as hexadecimal '''0xC3BA''' in UTF-8, as '''0x00FA''' in UTF-16 and as '''0xFA''' in latin-1/ISO8859-1/CP-1252. {{{#!highlight python #utf-8 data utf81 ='\xc3\xba' # convert from utf-8 to unicode unic = utf81.decode('utf-8') for c in unic: print '%04X'%(ord(c)) # convert from unicode to latin1/ISO8859-1 CP-1252 lat1=unic.encode('latin1') for c in lat1: print '%02X'%(ord(c)) }}} == Utf-8 and Unicode == {{{#!highlight python utf81='\xe1\xb7\x97' #utf-8 data unic = utf81.decode('utf-8') #converts from utf-8 to unicode (utf-16) for c in unic: print '%04X'%(ord(c)) type(unic) # unicode, 2 bytes per char type(utf81) # str, 1 bytes per char }}} == Time and date == {{{#!highlight python import time # get seconds since epoch until now in UTC to a string year-month-dayThour:minute:second strutc = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime() ) # get seconds since epoch until now in localtime to a string year-month-dayThour:minute:second strlocal = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime() ) # number seconds since epoch nrSeconds = time.mktime(time.gmtime()) nrSeconds = time.time() #usually is UTC on all OS # from timestamp to string date import datetime print(datetime.datetime.fromtimestamp(1284101485).strftime('%Y-%m-%d %H:%M:%S')) # def toUTCDateStr(timestamp): return datetime.datetime.utcfromtimestamp( timestamp ).strftime('%Y-%m-%d %H:%M:%S ') # timedelta import datetime x=datetime.datetime.fromtimestamp(1284101485) nowx=datetime.datetime.now() ts=(nowx-x).total_seconds() print int(ts) }}} == Write and reading data for a plist file == A plist file stores data in XML format. {{{#!highlight python import plistlib value = [{'key1':123,'key2':'asdf'},{'keyx1':'testing','keyz1':'yup'}] # save value in plist file plistlib.writePlist(value,'/tmp/plist1.plist') o=plistlib.readPlist('/tmp/plist1.plist') print o }}} Content of the file '''/tmp/plist1.plist''' {{{#!highlight xml key1 123 key2 asdf keyx1 testing keyz1 yup }}} == Threading == {{{#!highlight python #!/usr/bin/python # timestable.py # calculates the times table in concurrency import threading import time class TimesTable (threading.Thread): def __init__(self, timesTable): threading.Thread.__init__(self) #required self.timeTable = timesTable self.count = 1 def run(self): loop=True while loop: time.sleep(1) #sleep for 1 second result=self.timeTable * self.count print "%d*%d=%d"%(self.timeTable,self.count,result) if self.count<10: self.count = self.count+1 else: self.count=1 # create threads timesTable2 = TimesTable(2) timesTable5 = TimesTable(7) # start the threads timesTable2.start() timesTable5.start() }}} == unit tests == {{{#!highlight python import unittest class SimpleWidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() self.widget = None }}} == cython == Installation: * su * cd /tmp * wget http://cython.org/release/Cython-0.19.1.tar.gz * tar xvzf Cython-0.19.1.tar.gz * cd Cython-0.19.1 * python setup.py build * python setup.py install == pymssql == Requires cython. Installation: * su * cd /tmp * wget [[http://pymssql.googlecode.com/files/pymssql-2.0.0b1-dev-20111019.tar.gz]] * tar xvvzf pymssql-2.0.0b1-dev-20111019.tar.gz * cd pymssql-2.0.0b1-dev-20111019 * python setup.py build * python setup.py install * python * import pymssql == pywhois == Python module for retrieving WHOIS information of domains [[http://code.google.com/p/pywhois/]]. Fetch code with mercurial: * cd /tmp * hg clone https://code.google.com/p/pywhois/ * cd pywhois * python setup.py build * python setup.py install == Syntax highlighting on Vim for wsgi == Edit ~./.vimrc: {{{#!highlight bash syntax on filetype on au BufNewFile,BufRead *.wsgi set filetype=python }}} == Get file modification time == {{{#!highlight python import os nrSeconds=os.path.getmtime('/folder/file') # unix epoch, nr secs since 1970-01-01 00:00:00 }}} == Kill process with PID == {{{#!highlight python import os import signal os.kill(pid,signal.SIGTERM) }}} == Log message to /var/log/messages or /var/log/syslog == {{{#!highlight python import syslog syslog.syslog(syslog.LOG_INFO,'message to syslog') }}} == Simple process monitor == {{{#!highlight python # example service, dummyService.py import time while True: try: f=open('filex.log','wb') f.write('%f'%(time.time())) f.close() time.sleep(5) except KeyboardInterrupt: quit() }}} {{{#!highlight python #service monitor.py # * * * * * /usr/bin/python /home/vitor/svc/monitor.py import os import syslog import subprocess if __name__=="__main__": files = os.listdir('/proc') script="dummyService.py" prefix="dummyService:" svcRunning=False for file in files: if file.isdigit(): cmdline = open('/proc/%s/cmdline'%(file),'r').read() proc = "%s %s "%(file,cmdline) if script in proc : svcRunning=True if svcRunning==False: syslog.syslog(syslog.LOG_INFO,'%s process created '%(prefix) ) subprocess.Popen(['/usr/bin/python','dummyService.py'],cwd='/home/userx/svc') }}}