之前使用過py2exe 去產生 python 程式的 單一執行檔(click here),後來我安裝了pythonxy 去開發GUI 程式,我程式有用到 Enthought 的Traits UI/Traits 套件,雖然開發GUI 程式很快,我也從中學到MVC 的概念,不過我想要用 py2exe 去產生有引用 Traits UI/Traits 的執行檔時,一直無法成功,enthought 也回答我的疑問,我是有看沒有懂,所以只好去另找方法後來,
到 用Python 科學計算中文版 問了作者,他介紹與教我 用 bbfreeze 去產生執行檔,這個bbfreeze 產生的東西,應該算是建立一個環境給你寫的程式執行,所以會產生一個很大的Folder,不過可以用就好。
以下介紹方法:
1.bbfreeze 的setup 寫法:
#This script is for bbfreeze
#It generate execute file.
#Usage : python setup.py
from bbfreeze import Freezer
f = Freezer("Base64gui-1.0")
f.addScript("base64gui.py",gui_only=True)
f() # starts the freezing process
2.py2exe 要引用pyqt4 的setup 寫法:
#This script is for py2exe module
#It generate execute file.
#Usage : python setup.py py2exe
from distutils.core import setup
import py2exe
setup(windows=[{"script" : "d:/base64gui/py2exe/findandreplacedlg.py"}], options={"py2exe" : {"includes" : ["sip", "PyQt4"]}})
-----2012/12/14 update --------
另一個 產生 stand-alone executables 工具- PyInstaller (我測試的OS 是 windows xp)
要先裝 pywin32,使用方法
python pyinstaller.py yourpgm.py
它會產生 yourpgm folder,理面有個 dist 目錄 ,就會找到 yourpgm.exe 檔
2012年12月14日 星期五
2012年12月11日 星期二
2012年11月22日 星期四
HTTP Server ,socketserver,Acess enscribe file.
1.Python 提供 HTTP server,socketserver for http server and tcpip server.
2.Nonstop server 可以執行 ptyhon HTTP server.
Usage : python -m SimpleHTTPServer 8000
Note : -m : module , port number:8000
執行後, open web browser , "http://192.168.110.93:8000/ ,可以看到 Nonstop 的目錄
3.Python 可以 I/O Nonstop Guardian file.
READ Enscribe file (code 101,180) 沒問題
Write file ,File code 是 180 (ASCII C edit file).
可以使用 CTOEDIT 轉成 code 100. Usage: CTOEDIT C-file,EDIT-file.
同理, Edit file(Code 100) 也可以轉成 Code 180.Usage:EDITTOC Edit-file,C-file.
2.Nonstop server 可以執行 ptyhon HTTP server.
Usage : python -m SimpleHTTPServer 8000
Note : -m : module , port number:8000
執行後, open web browser , "http://192.168.110.93:8000/ ,可以看到 Nonstop 的目錄
3.Python 可以 I/O Nonstop Guardian file.
READ Enscribe file (code 101,180) 沒問題
Write file ,File code 是 180 (ASCII C edit file).
可以使用 CTOEDIT 轉成 code 100. Usage: CTOEDIT C-file,EDIT-file.
同理, Edit file(Code 100) 也可以轉成 Code 180.Usage:EDITTOC Edit-file,C-file.
2012年4月10日 星期二
virtualenv 安裝 PIL on Window XP
Python /virtualenv 安裝 PIL
方法1:
create virtualenv - virtualenv --no-site-package d:\pinax
activate virtualenv
pip install PIL (失敗)
方法 2:
在原本安裝的 python ,先裝PIL
create virtualenv - virtualenv --system-site-packges d:\pinax
這樣 PIL 就可以利用 virtualenv 的 "--system-site-packges" 把 PIL 的功能繼承過來
方法1:
create virtualenv - virtualenv --no-site-package d:\pinax
activate virtualenv
pip install PIL (失敗)
方法 2:
在原本安裝的 python ,先裝PIL
create virtualenv - virtualenv --system-site-packges d:\pinax
這樣 PIL 就可以利用 virtualenv 的 "--system-site-packges" 把 PIL 的功能繼承過來
用Python 產生 HTTP 檔案分享服務
1.切換到你要分享的目錄
2 python -m SimpleHTTPServer xxxx (defult 8000, 你可改成你要的port)
3. http://127.0.0.1:8000/
4.有圖有真像
2 python -m SimpleHTTPServer xxxx (defult 8000, 你可改成你要的port)
3. http://127.0.0.1:8000/
4.有圖有真像
2011年11月24日 星期四
Nonstop NTP client demo
# Program name = ntp.py
# This program is for Nonstop server NTP client
# prerequirements : HP Nonstop OSS , Pyhton 2.4.2 (get it from ITUGLIB,http://ituglib.connect-community.org), and
# donwload ntplib-0.1.9 from Python Package Index
# You have to modify ntplib.py in ntplib-0.1.9 to accept ip address NTP. Here is snippet
# def request(self, host, version=2, port='ntp'):
# """make a NTP request to a server - return a NTPStats object"""
# # lookup server address
# #addrinfo = socket.getaddrinfo(host, port)[0]
# #family, sockaddr = addrinfo[0], addrinfo[4]
# family=2
# sockaddr=(host,123)
# You need to use Super Group to run the program.Because SETTIME is Super Group ONLY.
# Usage : gtacl -c "$(python ntp.py)"
import ntplib
import os
from time import ctime
c = ntplib.NTPClient()
response = c.request('XXX.XXX.XXX.XXX', version=3)
response.offset
response.version
ntptime=ctime(response.tx_time)
ntptimelist =ntptime.split()
newtime=ntptimelist[1]+' '+ntptimelist[2]+' '+ntptimelist[4]+','+ntptimelist[3]
#print ntplib.leap_to_text(response.leap)
#print response.root_delay
settimestring = "settime"+' '+newtime
#print settimestring
print "time"
#os.system('gtacl -c "time"')
#os.system('gtacl -c "status *"')
#os.system('gtacl -p fup "info \uitc.\$dev.cup.*"')
2011年1月5日 星期三
Python 2D 軟體
寫下python 2D/3D 軟體,避免忘記:
2.Pylab:就是 matplotlib
1.Gnuplot :
優點: 有GUI 可以互動式學習指令,上手容易,也有3D 的功能,也可以 programming with python
缺點:圖沒有很漂亮
2.Pylab:就是 matplotlib
優點:
缺點:
3.Enthought 的Chaco 2D 繪圖軟體:
優點:畫面漂亮,
缺點:沒有互動式GUI 可以玩
- 介紹 Chaco 2D 用Ipython 指令方式繪圖:
1.啟動Ipython
>> import numpy as np
>> from enthought.chaco.shell import *
>> x=np.array([1,2,3,4,5])
>> y1=np.array([2,3,4,5,6])
>> y2 =np.array([4,5,6,7,8])
>> plot(x,y1,'r.')
>> hold()
>> plot(x,y2,'g+',marker_size =10)
>> title('First Plot')
>> show()

- Chaco programming 方式:
可以到 Chaco 的網站有很多Sample code 可參考,另外
安裝chaco 後,在 chaco/example/ 底下也有很多sample 可以學習
2010年5月5日 星期三
Python 2D 軟體
寫下python 2D 軟體,避免忘記,python 的2D 繪圖軟體,

現行使用2個,介紹如下:
1.Gnuplot :
優點: 有GUI 可以互動式學習指令,上手容易,也有3D 的功能,也可以 programming with python
缺點:圖沒有很漂亮
2.Enthought 的Chaco 2D 繪圖軟體:
優點:畫面漂亮,
缺點:沒有互動式GUI 可以玩
3.介紹 Chaco 2D 用Ipython 指令方式繪圖:
1.啟動Ipython
>> import numpy as np
>> from enthought.chaco.shell import *
>> x=np.array([1,2,3,4,5])
>> y1=np.array([2,3,4,5,6])
>> y2 =np.array([4,5,6,7,8])
>> plot(x,y1,'r.')
>> hold()
>> plot(x,y2,'g+',marker_size =10)
>> title('First Plot')
>> show()
4. Chaco programming 方式:
可以到 Chaco 的網站有很多Sample code 可參考,另外
安裝chaco 後,在 chaco/example/ 底下也有很多sample 可以學習
2010年1月29日 星期五
Python 文件產生方法 - Sphinx 產生PDF 中文解法
Sphinx 是利用rst 文件 去產生 html、latex、pdf 等等的文件產生工具,
現行產生pdf 會碰到 中文字無處理的問題,解決方案:
1. rst 轉 Latex ,Latex 再轉 pdf
a. 找出 sphinx-quickstart 產生的project folder
b.在 project-folder/source 找出 conf.py
c.edit conf.py 找到以下並修改為:
latex_preamble = '''\usepackage{CJKutf8}\n\AtBeginDocument{\\begin{CJK}{UTF8}{bsmi}}\n\AtEndDocument{\end{CJK}}'''
source_encoding = 'utf-8'
d.再利用產出的 latex 文件去轉成 pdf
e.如何安裝 latex 與 CJK (Chineses/Japan/Korea) 字型 請參考:
在Windows 下使用LaTeX
現行產生pdf 會碰到 中文字無處理的問題,解決方案:
1. rst 轉 Latex ,Latex 再轉 pdf
a. 找出 sphinx-quickstart 產生的project folder
b.在 project-folder/source 找出 conf.py
c.edit conf.py 找到以下並修改為:
latex_preamble = '''\usepackage{CJKutf8}\n\AtBeginDocument{\\begin{CJK}{UTF8}{bsmi}}\n\AtEndDocument{\end{CJK}}'''
source_encoding = 'utf-8'
d.再利用產出的 latex 文件去轉成 pdf
e.如何安裝 latex 與 CJK (Chineses/Japan/Korea) 字型 請參考:
在Windows 下使用LaTeX
Python 文件產生方法 - 工具篇
1.Code highlighter:
Pygments -http://pygments.org/
2.rStructure text 轉 PDF
rst2pdf -http://code.google.com/p/rst2pdf/
3.Docutils:Documentation Utilities
http://docutils.sourceforge.net/
4.Sphinx-Python document generator (會包含 docutils 的套件)
http://sphinx.pocoo.org/index.html
5.xhtml2pdf
http://www.xhtml2pdf.com/
6.ReportLab's Open Source Libraries
http://www.reportlab.com/software/opensource/
7.html5lib
Library for working with HTML documents
現行作法:
1. 用reStructureText 寫文件
2. rst2html.py 產生 html 檔 ------- 已完成.
3. html 檔用 pdfCreator 產生 PDF 檔 -- 已完成.
4. rst2pdf 產生 PDF 檔-已完成. 但需加入 styles 檔
5.xhtml2pdf.exe 產出的pdf 中文字碼為黑塊.
6.Sphinx 掛rst2pdf 的 pdfBuilder ,產生PDF 檔中文字碼為黑塊.
Pygments -http://pygments.org/
2.rStructure text 轉 PDF
rst2pdf -http://code.google.com/p/rst2pdf/
3.Docutils:Documentation Utilities
http://docutils.sourceforge.net/
4.Sphinx-Python document generator (會包含 docutils 的套件)
http://sphinx.pocoo.org/index.html
5.xhtml2pdf
http://www.xhtml2pdf.com/
6.ReportLab's Open Source Libraries
http://www.reportlab.com/software/opensource/
7.html5lib
Library for working with HTML documents
現行作法:
1. 用reStructureText 寫文件
2. rst2html.py 產生 html 檔 ------- 已完成.
3. html 檔用 pdfCreator 產生 PDF 檔 -- 已完成.
4. rst2pdf 產生 PDF 檔-已完成. 但需加入 styles 檔
5.xhtml2pdf.exe 產出的pdf 中文字碼為黑塊.
6.Sphinx 掛rst2pdf 的 pdfBuilder ,產生PDF 檔中文字碼為黑塊.
2010年1月27日 星期三
Python 文件產生方法 - rst2pdf 中文解法
目的: 使用讓 rst2pdf 去產生中文的 PDF 文件,rst2pdf 的功能是將 reStructureText 文件轉換成 PDF 檔
這份文件是說明如何讓它輸出 有中文的 PDF 檔
1.Q:如何安裝 rst2pdf:
A: easy_install rst2pdf
2.產生方式
解法1: 讓 rst2pdf 去讀外部的style 檔
rst2pdf -help 看到 -s 的作法
-s STYLESHEETS, --stylesheets=STYLESHEETS
A comma-separated list of custom stylesheets.Default=""
指令: rst2pdf -s xxx.style source.txt -o output.pdf
說明:
1.kaiu 應該是標楷體
2.source.txt 是 reStructureText 且需存成 utf-8 編碼的文件檔
3.xxx.style 的內容:
{
"embeddedFonts" : [["kaiu.ttf","kaiu.ttf","kaiu.ttf","kaiu.ttf"]],
"fontsAlias" : {
"stdFont": "kaiu",
"stdBold": "kaiu",
"stdItalic": "kaiu",
"stdBoldItalic": "kaiu",
"stdMono": "kaiu"
}
}
解法2: 修改 style.json
如: D:\Python26\Lib\site-packages\rst2pdf-0.12.3-py2.6.egg\rst2pdf\styles\styles.json
修改後內容:
"embeddedFonts" : [ ["kaiu.ttf","kaiu.ttf","kaiu.ttf","kaiu.ttf"]],
"stdFont": "kaiu",
"stdBold": "kaiu",
"stdItalic": "kaiu",
"stdBoldItalic": "kaiu",
"stdSans": "kaiu",
"stdSansBold": "kaiu",
"stdSansItalic": "kaiu",
"stdSansBoldItalic": "kaiu",
"stdMono": "kaiu",
"stdMonoItalic": "kaiu",
"stdMonoBold": "kaiu",
"stdMonoBoldItalic": "kaiu",
"stdSerif": "kaiu"
修改前內容:
"embeddedFonts" : [ ],
"stdFont": "Helvetica",
"stdBold": "Helvetica-Bold",
"stdItalic": "Helvetica-Oblique",
"stdBoldItalic": "Helvetica-BoldOblique",
"stdSans": "Helvetica",
"stdSansBold": "Helvetica-Bold",
"stdSansItalic": "Helvetica-Oblique",
"stdSansBoldItalic": "Helvetica-BoldOblique",
"stdMono": "Courier",
"stdMonoItalic": "Courier-Oblique",
"stdMonoBold": "Courier-Bold",
"stdMonoBoldItalic": "Courier-BoldOblique",
"stdSerif": "Times-Roman"
3.結論:
a.建議使用 解法 1 產生pdf檔,因為尚未解決 Sphinx 如何產生中文的PDF 檔
這份文件是說明如何讓它輸出 有中文的 PDF 檔
1.Q:如何安裝 rst2pdf:
A: easy_install rst2pdf
2.產生方式
解法1: 讓 rst2pdf 去讀外部的style 檔
rst2pdf -help 看到 -s 的作法
-s STYLESHEETS, --stylesheets=STYLESHEETS
A comma-separated list of custom stylesheets.Default=""
指令: rst2pdf -s xxx.style source.txt -o output.pdf
說明:
1.kaiu 應該是標楷體
2.source.txt 是 reStructureText 且需存成 utf-8 編碼的文件檔
3.xxx.style 的內容:
{
"embeddedFonts" : [["kaiu.ttf","kaiu.ttf","kaiu.ttf","kaiu.ttf"]],
"fontsAlias" : {
"stdFont": "kaiu",
"stdBold": "kaiu",
"stdItalic": "kaiu",
"stdBoldItalic": "kaiu",
"stdMono": "kaiu"
}
}
解法2: 修改 style.json
如: D:\Python26\Lib\site-packages\rst2pdf-0.12.3-py2.6.egg\rst2pdf\styles\styles.json
修改後內容:
"embeddedFonts" : [ ["kaiu.ttf","kaiu.ttf","kaiu.ttf","kaiu.ttf"]],
"stdFont": "kaiu",
"stdBold": "kaiu",
"stdItalic": "kaiu",
"stdBoldItalic": "kaiu",
"stdSans": "kaiu",
"stdSansBold": "kaiu",
"stdSansItalic": "kaiu",
"stdSansBoldItalic": "kaiu",
"stdMono": "kaiu",
"stdMonoItalic": "kaiu",
"stdMonoBold": "kaiu",
"stdMonoBoldItalic": "kaiu",
"stdSerif": "kaiu"
修改前內容:
"embeddedFonts" : [ ],
"stdFont": "Helvetica",
"stdBold": "Helvetica-Bold",
"stdItalic": "Helvetica-Oblique",
"stdBoldItalic": "Helvetica-BoldOblique",
"stdSans": "Helvetica",
"stdSansBold": "Helvetica-Bold",
"stdSansItalic": "Helvetica-Oblique",
"stdSansBoldItalic": "Helvetica-BoldOblique",
"stdMono": "Courier",
"stdMonoItalic": "Courier-Oblique",
"stdMonoBold": "Courier-Bold",
"stdMonoBoldItalic": "Courier-BoldOblique",
"stdSerif": "Times-Roman"
3.結論:
a.建議使用 解法 1 產生pdf檔,因為尚未解決 Sphinx 如何產生中文的PDF 檔
2009年11月12日 星期四
Python ctypes 使用方法(2)
介紹一些使用方法:
define C library 的 header 檔
define C library 的 header 檔
from ctypes import *
WS_MAX_USER_LEN=10
WS_MAX_PIN_LEN =4
WS_MAX_LMK_ID =1
WS_MAX_IP_ADDR_LEN =10
WS_MAX_LABEL=5
WS_MAX_DESC=10
WS_MAX_LOG_ENTRY_LEN=100
WS_MAX_ZMK_KEY_ID_LEN=10
WS_VOID=c_void_p
WS_BYTE=c_ubyte
WS_CHAR=WS_BYTE
WS_BOOL=WS_BYTE
WS_USHORT=c_ushort
WS_ULONG=c_ulong
WS_LONG=c_long
WS_RV=WS_ULONG
WS_UNIT_ID=WS_ULONG
WS_DEVICE_ID=WS_ULONG
WS_CLUSTER_ID=WS_ULONG
WS_FLAGS=WS_ULONG
WS_UNIT_TYPE=WS_ULONG
# WebSentry Specific Return Codes #
WSR_OK= 0x00000000
WSR_CANCEL = 0x00000001
WSR_HOST_MEMORY= 0x00000002
WSR_UNIT_ID_INVALID =0x00000003
WSR_GENERAL_ERROR=0x00000005
class WS_ITEM(Structure):
_fields_=[('pData',POINTER(WS_BYTE)),('len', WS_ULONG)]
class WS_VERSION(Structure):
_fields_=[('major', WS_BYTE), ('minor', WS_BYTE)]
from wapich import * #import python wrap data
from ctypes import *
libc=cdll.LoadLibrary('wapicd.dll')
WS_Initialize=libc.WS_Initialize #define function
WS_Initialize.restype=WS_RV # set return type = WS_RV, if none, always return int
rv=WSR_OK
rv=WS_Initialize()
if rv != WSR_OK:
print rv
else:
print 'WS_Initialize is Ok'
WS_GetInfo=libc.WS_GetInfo
WS_GetInfo.restype=WS_RV
myInfo=WS_INFO()
myInfo_p=pointer(myInfo)
myInfo_p.contents=myInfo # assign myInfo_ptr pointer to myInfo
rv=WSR_OK
rv=WS_GetInfo(myInfo_p)
if rv !=WSR_OK:
print rv
print myInfo.manufacturerID[:]
print myInfo.description[:]
print myInfo.version.major
print myInfo.version.minor
2009年11月6日 星期五
Python ctypes 使用方法(1)
因為要使用C libray ,所以要使用ctypes 去 wrap C function
from ctypes import *
from ctypes.util import find_library
print '---Begin Show----'
print find_library('c')
print windll.kernel32
print cdll.msvcrt
print find_library('wapicd')
libc=cdll.LoadLibrary("msvcr90.dll")
print "---------- char --------"
x=c_char_p("Hello World")
print x
print x.value
print sizeof(x)
print '---------- int ----------'
i=c_int(42)
print i
print i.value
p = create_string_buffer("Hello", 10)
print sizeof(p), repr(p.raw)
print "---------- Bo class---------------"
class Bo(object):
def __init__(self, number):
self._as_parameter_=number
bo=Bo(33)
printf = libc.printf
printf("%d bottles of beer \n", bo)
strchr=libc.strchr
print strchr('abcdef', ord('c'))
strchr.restype=c_char_p # set retyrn type is char_pointer
print strchr('abcdef', ord('d'))
print '----Passing by reference---------'
i=c_int()
f=c_float()
s=create_string_buffer('\000'*32)
print i.value, f.value, repr(s.value)
libc.sscanf("1 3.14 hello", "%d %f %s", byref(i), byref(f), s) #Passing by ref
print i.value, f.value, repr(s.value)
print '---- Pointer ---------'
ptr_i=pointer(i)
ptr_f=pointer(f)
ptr_s=pointer(s)
libc.sscanf("1 3.14 hello", "%d %f %s", ptr_i,ptr_f,ptr_s)
print i.value, f.value, repr(s.value)
print 'point of i:', ptr_i.contents
print 'point of f:', ptr_f.contents
print 'point of s:', ptr_s.contents
print '------------ Test Structure ---------'
class POINT(Structure):
_fields_=[('x', c_int), ('y', c_int)]
p=POINT(10, 20)
print p.x, p.y
def testptr(a):
b=POINT()
b=a
b.x=a.x+100
b.y=a.y+100
return b
testptr.restype=POINT()
g=testptr(p)
print g.x, g.y
測試結果:
---Begin Show----
msvcr90.dll
C:\WINDOWS\system32\wapicd.dll
---------- char --------
c_char_p('Hello World')
Hello World
4
---------- int ----------
c_long(42)
42
10 'Hello\x00\x00\x00\x00\x00'
---------- Bo class---------------
12838358
def
----Passing by reference byref()---------
0 0.0 ''
1 3.1400001049 'hello'
---- Pointer pointer()---------
1 3.1400001049 'hello'
point of i: c_long(1)
point of f: c_float(3.1400001049041748)
point of s:
------------ Test Structure ---------
10 20
110 120
2009年10月29日 星期四
Python in Plurk
因為看到Plurk 是可以用網路程式去發送訊息的,所以想說用Python 試試看,說明方法如下:
1.Install SimpleJSON
Ans: easy_install simplejson ,它會自動Download 到你的Python 目錄去
2.Download plurkapi ,Copy plurkapi.py 到 D:\Python26\Lib (這是我的python 目錄)
plurkapi download location
3.因為無法發中文,看來應該是沒宣告Coding ,所以在 plurkapi.py 加入
# *- coding: UTF-8 -*-
4.Sample Code 做法:
1.Install SimpleJSON
Ans: easy_install simplejson ,它會自動Download 到你的Python 目錄去
2.Download plurkapi ,Copy plurkapi.py 到 D:\Python26\Lib (這是我的python 目錄)
plurkapi download location
3.因為無法發中文,看來應該是沒宣告Coding ,所以在 plurkapi.py 加入
# *- coding: UTF-8 -*-
4.Sample Code 做法:
# *- coding: UTF-8 -*-
import plurkapi
import sys
# Create an API object.
# Pass in your own username and password to the "login" method.
#
plurk_api = plurkapi.PlurkAPI()
if plurk_api.login('nickname', 'password') == False:
print "Login failed!"
sys.exit(1)
plurk_api.addPlurk(lang='tr_ch',qualifier='says',content='中文化Say Hello 222222!!!')
2009年5月27日 星期三
NonStop Server 試用Python
目標:使用python 開發Client/Server Thread program
測試結果:Nonstop server 不支援 Thread,只能使用 fork 。
Client 程式:
Server 程式:
測試結果:Nonstop server 不支援 Thread,只能使用 fork 。
Client 程式:
#######################################################
## Demo:Opening a Client-Side Socket for Sending Data
#######################################################
print '#'*60
print '# Demo:Opening a Client-Side Socket for Sending Data'
print '#'*60
import thread
import sys,time,os
from socket import *
def client(id):
serverHost = '192.168.110.93'
serverPort = 12343
def now():
return time.ctime(time.time( ))
message = 'I am ID: %s' %id + '- Time: %s' %(now())
if len(sys.argv) > 1:
serverHost = sys.argv[1]
#Create a socket
sSock = socket(AF_INET, SOCK_STREAM)
try :
#Connect to server
sSock.connect((serverHost, serverPort))
except Exception, e:
sSock.close()
os._exit(0)
#Send messages
sSock.send(message)
data = sSock.recv(1024)
print 'Client received: ', data
sSock.close()
os._exit(0)
def main():
i=0
while True:
newpid = os.fork()
if newpid == 0:client(i)
i=i+1
if i > 10 :break
if __name__ =='__main__':
main()
Server 程式:
import SocketServer,time
myHost=''
myPort=12343
class MyClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
print 'Welcome Clinet:',self.client_address
while True:
data=self.request.recv(1024)
time.sleep(1)
if not data:break
print 'Send Back:',data
self.request.send(data)
self.request.close()
myaddr=(myHost,myPort)
server=SocketServer.ThreadingTCPServer(myaddr,MyClientHandler)
server.serve_forever()
2009年5月20日 星期三
Python 複利計算
都是同事問我複利計算,微積分早就還給老師了,不知公式如何,只好自個想啦!
Amt-定期定額
Rate-利率
Y1=Amt*(1+Rate)
Y2=(Y1+Amt)*(1+Rate)
Yn=(Yn-1+Amt)*(1+Rate)
Python sample 程式如下:
# Directory 解法
-------------------------------------------------
Amt-定期定額
Rate-利率
Y1=Amt*(1+Rate)
Y2=(Y1+Amt)*(1+Rate)
Yn=(Yn-1+Amt)*(1+Rate)
Python sample 程式如下:
# Directory 解法
f={}
base=100
rate =0.05
f[1]=base*(1+rate)
i=1
for i in range(2,5):
f[i]=(f[i-1]+base)*(1+rate)
for key in f:
print key,f[key]
#Generator 解法def f(first,n):
while True:
result= (first+100)*(1.05)
first=result
n=n+1
print n,first
yield first
base=100
rate =0.05
i=1
gh=f(0,0)
for i in range(1,5):
gh.next()
-------------------------------------------------
2009年5月6日 星期三
Python Network Programming
1.Basic Socket Usage
Python is using only two communication domains: UNIX(AF_UNIX) and Internet domains(AF_INET)
2.1Create Socket
socket(family, type [, proto ])
family =AF_INET,AF_UNIX
type=SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET,SOCK_RDM
TCP 連接語法:sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) UDP 連接語法:sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2.2Connecting a socket and data transfer
Internet domain: sock.connect(('localhost', 8000))
UNIX domain:sock.connect('/tmp/sock')
2.3 Binding a name to socket
Internet domain:sock.bind(('localhost', 8000))
UNIX domain:sock.bind('/tmp/sock')
2.4 Listening and accepting connections
sock.listen(5)
clisock, address = sock.accept()
TCP servers 固定流程:bind-listen-accept
TCP socket is connection-oriented; when a client wants to speak to a particular server it must
connect itself, wait until the server accepts the connection, exchange data then close.
2.5 UDP sockets(保留待釐清)
Data packets are send and received with the sendto(data, address ) and recvfrom(buffer[, flags ]) methods
2.6 Closing the Socket
socket.close()
記得:一定要Close a socket 才能再使用它
2.7 Socket Module 常用的function
socket.getfqdn('www.yahoo.com.tw) -return the \Fully Qualied Domain Name"
>>'w2.rd.vip.tw1.yahoo.com'
>>> socket.getfqdn()
'UT09002311.uitctech.com.tw'
gethostbyname(hostname )- Get IP address
>>> socket.gethostbyname('www.yahoo.com.tw')
'119.160.246.23'
>>> socket.gethostbyname_ex('www.yahoo.com.tw')
('tw1-w2.rd.tw.g1.b.yahoo.com', ['www.yahoo.com.tw', 'rc.tpe.yahoo.com', 'tw.rc.yahoo.com', 'w2.rd.tw.g1.b.yahoo.com'], ['119.160.246.23'])
gethostbyaddr(ipaddr )-Get Host name
>>> socket.gethostbyaddr('127.0.0.1')
('localhost', [], ['127.0.0.1'])
>>> socket.gethostbyaddr('119.160.246.23')
('w2.rd.vip.tw1.yahoo.com', [], ['119.160.246.23'])
getservbyname(servname )-轉換 service 變成port
>>> socket.getservbyname('ftp')
21
getprotobyname('ICMP')- 轉換protocol 變成corresponding number
>>> socket.getprotobyname('ICMP')
1
其它:
Function Name Synopsis
htons(sint ) Convert short integer from host to network format
ntohs(sint ) Convert short integer from network to host format
htonl(lint ) Convert long integer from host to network format
ntohl(lint ) Convert long integer from network to host
3.基本網路Flow 設計
TCP Model:(只能處理單一Client)
![]()
![]()
![]()
Echo server sample code:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8000))
serversocket.listen(1)
clientsocket, clientaddress = serversocket.accept()
print 'Connection from ', clientaddress
while 1:
data = clientsocket.recv(1024)
if not data: break
clientsocket.send(data)
clientsocket.close()
Echo client sample code:
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
while 1:
data = raw_input('>')
clientsocket.send(data)
if not data: break
newdata = clientsocket.recv(1024)
print newdata
clientsocket.close()
UDP Echo server sample code:
# -*- Coding:Utf-8 -*-
# UDP model
from socket import *
ssock=socket(AF_INET,SOCK_DGRAM)
ssock.bind(('localhost',9999))
while 1:
data,addr =ssock.recvfrom(1024)
if not data:break
ssock.sendto(data,addr)
ssock.close()
UDP Echo client sample code:
from socket import *
ssock = socket(AF_INET,SOCK_DGRAM)
while 1:
data = raw_input('>')
ssock.sendto(data, ('localhost', 9999))
if not data: break;
newdata = ssock.recvfrom(1024)
print newdata
ssock.close()
4.處理多個Client 的Server 方式:
Thread-server.py
############################################################################# # Server side: open a socket on a port, listen for a message from a client, # and send an echo reply; echoes lines until eof when client closes socket; # spawns a thread to handle each client connection; threads share global # memory space with main thread; this is more portable than fork: threads # work on standard Windows systems, but process forks do not; ############################################################################# import thread, time from socket import * # get socket constructor and constants myHost = '127.0.0.1' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # allow up to 5 pending connects def now( ): return time.ctime(time.time( )) # current time on the server def handleClient(connection): # in spawned thread: reply time.sleep(5) # simulate a blocking activity while True: # read, write a client socket data = connection.recv(1024) if not data: break connection.send('Echo=>%s at %s' % (data, now( ))) connection.close( ) def dispatcher( ): # listen until process killed while True: # wait for next connection, connection, address = sockobj.accept( ) # pass to thread for service print 'Server connected by', address, print 'at', now( ) thread.start_new(handleClient, (connection,)) dispatcher( )
Class-socket.py
#############################################################################
# Server side: open a socket on a port, listen for a message from a client,
# and send an echo reply; this version uses the standard library module
# SocketServer to do its work; SocketServer allows us to make a simple
# TCPServer, a ThreadingTCPServer, a ForkingTCPServer, and more, and
# routes each client connect request to a new instance of a passed-in
# request handler object's handle method; SocketServer also supports
# UDP and Unix domain sockets; see the library manual for other usage.
#############################################################################
import SocketServer, time # get socket server, handler objects
myHost = '' # server machine, '' means local host
myPort = 50007 # listen on a non-reserved port number
def now( ):
return time.ctime(time.time( ))
class MyClientHandler(SocketServer.BaseRequestHandler):
def handle(self): # on each client connect
print self.client_address, now( ) # show this client's address
time.sleep(5) # simulate a blocking activity
while True: # self.request is client socket
data = self.request.recv(1024) # read, write a client socket
if not data: break
self.request.send('Echo=>%s at %s' % (data, now( )))
self.request.close( )
# make a threaded server, listen/handle clients forever
myaddr = (myHost, myPort)
server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler)
server.serve_forever( )
Select-server.py
#############################################################################
# Server: handle multiple clients in parallel with select. use the select
# module to manually multiplex among a set of sockets: main sockets which
# accept new client connections, and input sockets connected to accepted
# clients; select can take an optional 4th arg--0 to poll, n.m to wait n.m
# seconds, or ommitted to wait till any socket is ready for processing.
#############################################################################
import sys, time
from select import select
from socket import socket, AF_INET, SOCK_STREAM
def now(): return time.ctime(time.time( ))
myHost = '' # server machine, '' means local host
myPort = 50007 # listen on a non-reserved port number
if len(sys.argv) == 3: # allow host/port as cmdline args too
myHost, myPort = sys.argv[1:]
numPortSocks = 2 # number of ports for client connects
# make main sockets for accepting new client requests
mainsocks, readsocks, writesocks = [], [], []
for i in range(numPortSocks):
portsock = socket(AF_INET, SOCK_STREAM) # make a TCP/IP spocket object
portsock.bind((myHost, myPort)) # bind it to server port number
portsock.listen(5) # listen, allow 5 pending connects
mainsocks.append(portsock) # add to main list to identify
readsocks.append(portsock) # add to select inputs list
myPort += 1 # bind on consecutive ports
# event loop: listen and multiplex until server process killed
print 'select-server loop starting'
while True:
#print readsocks
readables, writeables, exceptions = select(readsocks, writesocks, [])
for sockobj in readables:
if sockobj in mainsocks: # for ready input sockets
# port socket: accept new client
newsock, address = sockobj.accept( ) # accept should not block
print 'Connect:', address, id(newsock) # newsock is a new socket
readsocks.append(newsock) # add to select list, wait
else:
# client socket: read next line
data = sockobj.recv(1024) # recv should not block
print '\tgot:', data, 'on', id(sockobj)
if not data: # if closed by the clients
sockobj.close( ) # close here and remv from
readsocks.remove(sockobj) # del list else reselected
else:
# this may block: should really select for writes too
sockobj.send('Echo=>%s at %s' % (data, now( )))
Python is using only two communication domains: UNIX(AF_UNIX) and Internet domains(AF_INET)
2.1Create Socket
socket(family, type [, proto ])
family =AF_INET,AF_UNIX
type=SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET,SOCK_RDM
TCP 連接語法:sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) UDP 連接語法:sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2.2Connecting a socket and data transfer
Internet domain: sock.connect(('localhost', 8000))
UNIX domain:sock.connect('/tmp/sock')
2.3 Binding a name to socket
Internet domain:sock.bind(('localhost', 8000))
UNIX domain:sock.bind('/tmp/sock')
2.4 Listening and accepting connections
sock.listen(5)
clisock, address = sock.accept()
TCP servers 固定流程:bind-listen-accept
TCP socket is connection-oriented; when a client wants to speak to a particular server it must
connect itself, wait until the server accepts the connection, exchange data then close.
2.5 UDP sockets(保留待釐清)
Data packets are send and received with the sendto(data, address ) and recvfrom(buffer[, flags ]) methods
2.6 Closing the Socket
socket.close()
記得:一定要Close a socket 才能再使用它
2.7 Socket Module 常用的function
socket.getfqdn('www.yahoo.com.tw) -return the \Fully Qualied Domain Name"
>>'w2.rd.vip.tw1.yahoo.com'
>>> socket.getfqdn()
'UT09002311.uitctech.com.tw'
gethostbyname(hostname )- Get IP address
>>> socket.gethostbyname('www.yahoo.com.tw')
'119.160.246.23'
>>> socket.gethostbyname_ex('www.yahoo.com.tw')
('tw1-w2.rd.tw.g1.b.yahoo.com', ['www.yahoo.com.tw', 'rc.tpe.yahoo.com', 'tw.rc.yahoo.com', 'w2.rd.tw.g1.b.yahoo.com'], ['119.160.246.23'])
gethostbyaddr(ipaddr )-Get Host name
>>> socket.gethostbyaddr('127.0.0.1')
('localhost', [], ['127.0.0.1'])
>>> socket.gethostbyaddr('119.160.246.23')
('w2.rd.vip.tw1.yahoo.com', [], ['119.160.246.23'])
getservbyname(servname )-轉換 service 變成port
>>> socket.getservbyname('ftp')
21
getprotobyname('ICMP')- 轉換protocol 變成corresponding number
>>> socket.getprotobyname('ICMP')
1
其它:
Function Name Synopsis
htons(sint ) Convert short integer from host to network format
ntohs(sint ) Convert short integer from network to host format
htonl(lint ) Convert long integer from host to network format
ntohl(lint ) Convert long integer from network to host
3.基本網路Flow 設計
TCP Model:(只能處理單一Client)
UDP Model:(只能處理單一Client)
Echo server sample code:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8000))
serversocket.listen(1)
clientsocket, clientaddress = serversocket.accept()
print 'Connection from ', clientaddress
while 1:
data = clientsocket.recv(1024)
if not data: break
clientsocket.send(data)
clientsocket.close()
Echo client sample code:
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
while 1:
data = raw_input('>')
clientsocket.send(data)
if not data: break
newdata = clientsocket.recv(1024)
print newdata
clientsocket.close()
UDP Echo server sample code:
# -*- Coding:Utf-8 -*-
# UDP model
from socket import *
ssock=socket(AF_INET,SOCK_DGRAM)
ssock.bind(('localhost',9999))
while 1:
data,addr =ssock.recvfrom(1024)
if not data:break
ssock.sendto(data,addr)
ssock.close()
UDP Echo client sample code:
from socket import *
ssock = socket(AF_INET,SOCK_DGRAM)
while 1:
data = raw_input('>')
ssock.sendto(data, ('localhost', 9999))
if not data: break;
newdata = ssock.recvfrom(1024)
print newdata
ssock.close()
4.處理多個Client 的Server 方式:
Thread-server.py
############################################################################# # Server side: open a socket on a port, listen for a message from a client, # and send an echo reply; echoes lines until eof when client closes socket; # spawns a thread to handle each client connection; threads share global # memory space with main thread; this is more portable than fork: threads # work on standard Windows systems, but process forks do not; ############################################################################# import thread, time from socket import * # get socket constructor and constants myHost = '127.0.0.1' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # allow up to 5 pending connects def now( ): return time.ctime(time.time( )) # current time on the server def handleClient(connection): # in spawned thread: reply time.sleep(5) # simulate a blocking activity while True: # read, write a client socket data = connection.recv(1024) if not data: break connection.send('Echo=>%s at %s' % (data, now( ))) connection.close( ) def dispatcher( ): # listen until process killed while True: # wait for next connection, connection, address = sockobj.accept( ) # pass to thread for service print 'Server connected by', address, print 'at', now( ) thread.start_new(handleClient, (connection,)) dispatcher( )
Class-socket.py
#############################################################################
# Server side: open a socket on a port, listen for a message from a client,
# and send an echo reply; this version uses the standard library module
# SocketServer to do its work; SocketServer allows us to make a simple
# TCPServer, a ThreadingTCPServer, a ForkingTCPServer, and more, and
# routes each client connect request to a new instance of a passed-in
# request handler object's handle method; SocketServer also supports
# UDP and Unix domain sockets; see the library manual for other usage.
#############################################################################
import SocketServer, time # get socket server, handler objects
myHost = '' # server machine, '' means local host
myPort = 50007 # listen on a non-reserved port number
def now( ):
return time.ctime(time.time( ))
class MyClientHandler(SocketServer.BaseRequestHandler):
def handle(self): # on each client connect
print self.client_address, now( ) # show this client's address
time.sleep(5) # simulate a blocking activity
while True: # self.request is client socket
data = self.request.recv(1024) # read, write a client socket
if not data: break
self.request.send('Echo=>%s at %s' % (data, now( )))
self.request.close( )
# make a threaded server, listen/handle clients forever
myaddr = (myHost, myPort)
server = SocketServer.ThreadingTCPServer(myaddr, MyClientHandler)
server.serve_forever( )
Select-server.py
#############################################################################
# Server: handle multiple clients in parallel with select. use the select
# module to manually multiplex among a set of sockets: main sockets which
# accept new client connections, and input sockets connected to accepted
# clients; select can take an optional 4th arg--0 to poll, n.m to wait n.m
# seconds, or ommitted to wait till any socket is ready for processing.
#############################################################################
import sys, time
from select import select
from socket import socket, AF_INET, SOCK_STREAM
def now(): return time.ctime(time.time( ))
myHost = '' # server machine, '' means local host
myPort = 50007 # listen on a non-reserved port number
if len(sys.argv) == 3: # allow host/port as cmdline args too
myHost, myPort = sys.argv[1:]
numPortSocks = 2 # number of ports for client connects
# make main sockets for accepting new client requests
mainsocks, readsocks, writesocks = [], [], []
for i in range(numPortSocks):
portsock = socket(AF_INET, SOCK_STREAM) # make a TCP/IP spocket object
portsock.bind((myHost, myPort)) # bind it to server port number
portsock.listen(5) # listen, allow 5 pending connects
mainsocks.append(portsock) # add to main list to identify
readsocks.append(portsock) # add to select inputs list
myPort += 1 # bind on consecutive ports
# event loop: listen and multiplex until server process killed
print 'select-server loop starting'
while True:
#print readsocks
readables, writeables, exceptions = select(readsocks, writesocks, [])
for sockobj in readables:
if sockobj in mainsocks: # for ready input sockets
# port socket: accept new client
newsock, address = sockobj.accept( ) # accept should not block
print 'Connect:', address, id(newsock) # newsock is a new socket
readsocks.append(newsock) # add to select list, wait
else:
# client socket: read next line
data = sockobj.recv(1024) # recv should not block
print '\tgot:', data, 'on', id(sockobj)
if not data: # if closed by the clients
sockobj.close( ) # close here and remv from
readsocks.remove(sockobj) # del list else reselected
else:
# this may block: should really select for writes too
sockobj.send('Echo=>%s at %s' % (data, now( )))
2009年4月26日 星期日
Google App Engine (1)
for Beginner who using Google App Engine and memo for myself.
Resource :
1.Google App Engine(GAE)
2.Docs
1.Download and install at C:\Google\google_appengine
Two pyhton programs thats your need to know first.
a.dev_appserver.py, the development web server(在自己電腦用的Web server)
b.appcfg.py, for uploading your app to App Engine(Upload 到你的App Host)
2.Create your folder(project) like C:\helloworld
3. Create helloworld.py
print 'Content-Type: text/plain'
print ''
print 'Hello, world! Ray '
4.Create app.yaml
application: yehrayyeh
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: helloworld.py
5.在自己電腦測試
c:\helloworld>dev_appserver.py c:/helloworld
測試 URL http://localhost:8080/
6.放到 GAE 去看看, Google http://appengine.google.com/
方法如下:appcfg.py update c:/helloworld
Resource :
1.Google App Engine(GAE)
2.Docs
1.Download and install at C:\Google\google_appengine
Two pyhton programs thats your need to know first.
a.dev_appserver.py, the development web server(在自己電腦用的Web server)
b.appcfg.py, for uploading your app to App Engine(Upload 到你的App Host)
2.Create your folder(project) like C:\helloworld
3. Create helloworld.py
print 'Content-Type: text/plain'
print ''
print 'Hello, world! Ray '
4.Create app.yaml
application: yehrayyeh
version: 1
runtime: python
api_version: 1
handlers:
- url: /.*
script: helloworld.py
5.在自己電腦測試
c:\helloworld>dev_appserver.py c:/helloworld
測試 URL http://localhost:8080/
6.放到 GAE 去看看, Google http://appengine.google.com/
方法如下:appcfg.py update c:/helloworld
2009年1月7日 星期三
如何利用SVN 去自動備份
我在網路上找到的資料,來源
http://gael-varoquaux.info/computers/svnautocommit/index.html
1.準備工作:
a. SVN 軟體,因為要直接用command mode,請到以下 download:
http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91
version :svn-win32-1.5.5.zip
2.下載 svncommit.exe ,找一下可以看到
http://gael-varoquaux.info/computers/svnautocommit/index.html
Usage :svncommit.exe [path] => svncommit.exe c:\python-ray
3.因為它是利用排程去 啟動 svncommit.exe ,所以要先把要backup 的資料放到 svn server,
並且在啟動備份的機器上產生一份workcopy ,例如 c:\python-ray
4.利用控制台中的 -> 排定的工作 去設定
http://gael-varoquaux.info/computers/svnautocommit/index.html
1.準備工作:
a. SVN 軟體,因為要直接用command mode,請到以下 download:
http://subversion.tigris.org/servlets/ProjectDocumentList?folderID=91
version :svn-win32-1.5.5.zip
2.下載 svncommit.exe ,找一下可以看到
http://gael-varoquaux.info/computers/svnautocommit/index.html
Usage :svncommit.exe [path] => svncommit.exe c:\python-ray
3.因為它是利用排程去 啟動 svncommit.exe ,所以要先把要backup 的資料放到 svn server,
並且在啟動備份的機器上產生一份workcopy ,例如 c:\python-ray
4.利用控制台中的 -> 排定的工作 去設定
2008年12月5日 星期五
Python IDE-Eric 安裝介紹
What you need ?
1.Python 2.5.2
2.PyQt4 http://www.riverbankcomputing.co.uk/software/pyqt/download
PyQt-Py2.5-gpl-4.4.3-1.exe
3.Eric http://die-offenbachs.de/eric/index.html
a.unzip Eric -> 如 到 c:\eric4-4.2.3
b. python install.py
4.新增eric.bat shortcut 到 桌面
1.Python 2.5.2
2.PyQt4 http://www.riverbankcomputing.co.uk/software/pyqt/download
PyQt-Py2.5-gpl-4.4.3-1.exe
3.Eric http://die-offenbachs.de/eric/index.html
a.unzip Eric -> 如 到 c:\eric4-4.2.3
b. python install.py
4.新增eric.bat shortcut 到 桌面
訂閱:
文章 (Atom)
