Size: 6658
Comment:
|
Size: 9229
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 251: | Line 251: |
== Read URL content == {{{#!highlight python import urllib2 r=urllib2.urlopen('http://www.sapo.pt') resp=r.read() print resp }}} == Windows service == Install http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.5.exe/download for Python 2.5 for Windows. Adapted from http://ryrobes.com/python/running-python-scripts-as-a-windows-service/ {{{#!highlight python # C:\cmt\test>python testWinSvc.py install # C:\cmt\test>python testWinSvc.py start # C:\cmt\test>python testWinSvc.py stop # C:\cmt\test>python testWinSvc.py remove # C:\cmt\test>service.msc import win32service import win32serviceutil import win32api import win32con import win32event import win32evtlogutil import os, sys, string, time class aservice(win32serviceutil.ServiceFramework): _svc_name_ = "MyServiceShortName" _svc_display_name_ = "My Service Long Fancy Name!" _svc_description_ = "THis is what my crazy little service does - aka a DESCRIPTION! WHoa!" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, '')) self.timeout = 1000 #1 second # This is how long the service will wait to run / refresh itself (see script below) while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!") #For Event Log break else: try: handle = open('c:/windows/temp/outx1.txt', "a") handle.write('%s \n' % ('tst svc')) handle.close() except: pass def ctrlHandler(ctrlType): return True if __name__ == '__main__': win32api.SetConsoleCtrlHandler(ctrlHandler, True) win32serviceutil.HandleCommandLine(aservice) }}} |
Python
Python is a programming language that lets you work more quickly and integrate your systems more effectively.
Links:
UTF-8
At the start of source code files:
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.
Utf-8 and Unicode
Time and date
1 import time
2 # get seconds since epoch until now in UTC to a string year-month-dayThour:minute:second
3 strutc = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime() )
4 # get seconds since epoch until now in localtime to a string year-month-dayThour:minute:second
5 strlocal = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime() )
6 # number seconds since epoch
7 nrSeconds = time.mktime(time.gmtime())
8 nrSeconds = time.time() #usually is UTC on all OS
9 # from timestamp to string date
10 import datetime
11 print(datetime.datetime.fromtimestamp(1284101485).strftime('%Y-%m-%d %H:%M:%S'))
12 #
13 def toUTCDateStr(timestamp):
14 return datetime.datetime.utcfromtimestamp( timestamp ).strftime('%Y-%m-%d %H:%M:%S ')
15 # timedelta
16 import datetime
17 x=datetime.datetime.fromtimestamp(1284101485)
18 nowx=datetime.datetime.now()
19 ts=(nowx-x).total_seconds()
20 print int(ts)
Write and reading data for a plist file
A plist file stores data in XML format.
Content of the file /tmp/plist1.plist
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 <plist version="1.0">
4 <array>
5 <dict>
6 <key>key1</key>
7 <integer>123</integer>
8 <key>key2</key>
9 <string>asdf</string>
10 </dict>
11 <dict>
12 <key>keyx1</key>
13 <string>testing</string>
14 <key>keyz1</key>
15 <string>yup</string>
16 </dict>
17 </array>
18 </plist>
Threading
1 #!/usr/bin/python
2 # timestable.py
3 # calculates the times table in concurrency
4 import threading
5 import time
6
7 class TimesTable (threading.Thread):
8 def __init__(self, timesTable):
9 threading.Thread.__init__(self) #required
10 self.timeTable = timesTable
11 self.count = 1
12 def run(self):
13 loop=True
14 while loop:
15 time.sleep(1) #sleep for 1 second
16 result=self.timeTable * self.count
17 print "%d*%d=%d"%(self.timeTable,self.count,result)
18 if self.count<10:
19 self.count = self.count+1
20 else:
21 self.count=1
22
23 # create threads
24 timesTable2 = TimesTable(2)
25 timesTable5 = TimesTable(7)
26
27 # start the threads
28 timesTable2.start()
29 timesTable5.start()
unit tests
cython
Installation:
- su
- cd /tmp
- 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:
Get file modification time
Kill process with PID
Log message to /var/log/messages or /var/log/syslog
Simple process monitor
1 #service monitor.py
2 # * * * * * /usr/bin/python /home/vitor/svc/monitor.py
3 import os
4 import syslog
5 import subprocess
6
7 if __name__=="__main__":
8 files = os.listdir('/proc')
9 script="dummyService.py"
10 prefix="dummyService:"
11
12 svcRunning=False
13
14 for file in files:
15
16 if file.isdigit():
17 cmdline = open('/proc/%s/cmdline'%(file),'r').read()
18 proc = "%s %s "%(file,cmdline)
19
20 if script in proc :
21 svcRunning=True
22
23 if svcRunning==False:
24 syslog.syslog(syslog.LOG_INFO,'%s process created '%(prefix) )
25 subprocess.Popen(['/usr/bin/python','dummyService.py'],cwd='/home/userx/svc')
Read URL content
Windows service
Install http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.5.exe/download for Python 2.5 for Windows.
Adapted from http://ryrobes.com/python/running-python-scripts-as-a-windows-service/
1 # C:\cmt\test>python testWinSvc.py install
2 # C:\cmt\test>python testWinSvc.py start
3 # C:\cmt\test>python testWinSvc.py stop
4 # C:\cmt\test>python testWinSvc.py remove
5 # C:\cmt\test>service.msc
6 import win32service
7 import win32serviceutil
8 import win32api
9 import win32con
10 import win32event
11 import win32evtlogutil
12 import os, sys, string, time
13
14 class aservice(win32serviceutil.ServiceFramework):
15 _svc_name_ = "MyServiceShortName"
16 _svc_display_name_ = "My Service Long Fancy Name!"
17 _svc_description_ = "THis is what my crazy little service does - aka a DESCRIPTION! WHoa!"
18
19 def __init__(self, args):
20 win32serviceutil.ServiceFramework.__init__(self, args)
21 self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
22
23 def SvcStop(self):
24 self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
25 win32event.SetEvent(self.hWaitStop)
26
27 def SvcDoRun(self):
28 import servicemanager
29 servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, ''))
30 self.timeout = 1000 #1 second
31 # This is how long the service will wait to run / refresh itself (see script below)
32
33 while 1:
34 # Wait for service stop signal, if I timeout, loop again
35 rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
36 # Check to see if self.hWaitStop happened
37 if rc == win32event.WAIT_OBJECT_0:
38 # Stop signal encountered
39 servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!") #For Event Log
40 break
41 else:
42 try:
43 handle = open('c:/windows/temp/outx1.txt', "a")
44 handle.write('%s \n' % ('tst svc'))
45 handle.close()
46 except:
47 pass
48
49
50
51 def ctrlHandler(ctrlType):
52 return True
53
54 if __name__ == '__main__':
55 win32api.SetConsoleCtrlHandler(ctrlHandler, True)
56 win32serviceutil.HandleCommandLine(aservice)