sed 's/\t/ /g'
2010년 11월 29일 월요일
2010년 8월 6일 금요일
Python Thread Pool TCP Server 구현.
아래 링크를 참조하여 간단하게 Python Multithread Pool TCP Server 를 구현해 보았다.
http://code.activestate.com/recipes/574454/
http://www.cherrypy.org/browser/cherrypy/_cphttpserver.py?rev=1
TCP 서버 클래스 사용시 다중상속에 따른 생성자 호출이 복잡하고 생성자 인수를 변경하지 않기 위하여
인스턴스 생성후 별도의 초기화 메쏘드를 호출하는 방식을 택했다.
아래 소스를 보면 쉽게 이해할 수 있을 것이다.
아래 소스와 같은 폴더에 적당한 index.html 를 만들고 실행한 후 웹브라우저로 8002 포트에 접속해보자.
http://code.activestate.com/recipes/574454/
http://www.cherrypy.org/browser/cherrypy/_cphttpserver.py?rev=1
TCP 서버 클래스 사용시 다중상속에 따른 생성자 호출이 복잡하고 생성자 인수를 변경하지 않기 위하여
인스턴스 생성후 별도의 초기화 메쏘드를 호출하는 방식을 택했다.
아래 소스를 보면 쉽게 이해할 수 있을 것이다.
아래 소스와 같은 폴더에 적당한 index.html 를 만들고 실행한 후 웹브라우저로 8002 포트에 접속해보자.
import SocketServer
import Queue
import threading
import socket
class ThreadPoolMixIn(SocketServer.ThreadingMixIn):
'''
use a thread pool instead of a new thread on every request
'''
allow_reuse_address = True # seems to fix socket.error on server restart
def create_pool(self, numThreads):
# set up the threadpool
self.numThreads = numThreads
self.requests = Queue.Queue(self.numThreads)
self.threadPool = []
for x in range(self.numThreads):
t = threading.Thread(target = self.process_request_thread)
self.threadPool.append(t)
t.setDaemon(1)
t.start()
def process_request_thread(self):
'''
obtain request from queue instead of directly from server socket
'''
while True:
SocketServer.ThreadingMixIn.process_request_thread(self, *self.requests.get())
def process_request(self, request, client_address):
self.requests.put((request, client_address))
class ThreadPoolTCPServer(ThreadPoolMixIn, SocketServer.TCPServer):
pass
class ThreadPoolUDPServer(ThreadPoolMixIn, SocketServer.UDPServer):
pass
if __name__ == '__main__':
import SimpleHTTPServer
import SocketServer
def test(HandlerClass = SimpleHTTPServer.SimpleHTTPRequestHandler,
ServerClass = ThreadPoolTCPServer,
protocol="HTTP/1.0"):
'''
Test: Run an HTTP server on port 8002
'''
port = 8002
server_address = ('', port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
httpd.create_pool(10)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
test()
2010년 8월 5일 목요일
Python 라이브러리 소스패키지로 RPM 생성하기.
우분투나 데비안에는 레포지토리에 웬만한 파이썬라이브러리들이 다 포함되어 있지만,
CentOS 5.5 에는 별로 없을 뿐더러 그나마도 예전 버전이다.
필요한 라이브러리를 찾아서 수작업으로 설치해줘야 하는 상황이다. TT_TT.
아래처럼 설치하면 되지만 삭제,업그레이드를 수작업으로 해야되어서 왠지 찜찜.
그래서, CentOS 5.5상에서 RPM 패키지를 생성하기로 결정했다.
아래와 같이 하면 소스패키지에서 RPM 패키지를 생성할 수 있다고 한다.
하지만, 불행히도 아래와 같은 메시지를 보게 될 것이다.
우분투 10.4에서는 에러없이 생성된다.(이건 무슨 조화?)
포기할까 하다가 cx-Freeze 는 에러없이 RPM 패키지가 생성되는 것이다.
cx-Freeze 의 setup.py 를 분석하면 답이 있다.
먼저, 다음명령으로 라이브러리 빌드에는 문제가 없는지 확인한다.
여기서, 문제가 발생하는 건 각자 알아서 해결하자.(README 파일이나 홈페이지 참조)
cx-Freeze 소스를 받아서 압축해제하고 setup.py 를 열어보면 다음 내용을 볼 수 있을 것이다.
bdist_rpm 빌드명령을 커스터마이징하고 setup 에 등록해주면 되는 것이다.
다음은 ctypes 1.0.2 소스의 setup.py 를 수정한 부분이다.
자, 다시 RPM 패키지를 만들어보자.
몇몇패키지들은 RPM 생성중 오류가 나지만 로그메시지를 잘 보면 해결할 수 있을 것이다.
(root 권한으로 수행(cofigobj?), MANIFEST 파일삭제(pymssql?),
setup.cfg 수정(mysql-python) 등등등)
위방법으로 Cython, MySQL-python, configobj, ctypes, hashlib, importlib, multiprocessing,
pymssql, pyodbc, subprocess32, unittest2 소스패키지에서 RPM 패키지를 생성해냈다.
CentOS 5.5 에는 별로 없을 뿐더러 그나마도 예전 버전이다.
필요한 라이브러리를 찾아서 수작업으로 설치해줘야 하는 상황이다. TT_TT.
아래처럼 설치하면 되지만 삭제,업그레이드를 수작업으로 해야되어서 왠지 찜찜.
python setup.py install
egg 패키지도 완전삭제는 수작업으로 해야 되어서 역시 찜찜.그래서, CentOS 5.5상에서 RPM 패키지를 생성하기로 결정했다.
아래와 같이 하면 소스패키지에서 RPM 패키지를 생성할 수 있다고 한다.
python setup.py bdist_rpm
하지만, 불행히도 아래와 같은 메시지를 보게 될 것이다.
파일 처리 중: ctypes-1.0.2-1
Provides: _ctypes.so _ctypes_test.so
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Requires: libc.so.6 libc.so.6(GLIBC_2.0) libc.so.6(GLIBC_2.1) libc.so.6(GLIBC_2.1.3) libc.so.6(GLIBC_2.3.4) libc.so.6(GLIBC_2.4) libpthread.so.0 python(abi) = 2.4 rtld(GNU_HASH)
파일 처리 중: ctypes-debuginfo-1.0.2-1
Provides: _ctypes.so.debug _ctypes_test.so.debug
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/tmp/ctypes-1.0.2-1-buildroot
오류: Installed (but unpackaged) file(s) found:
/usr/lib/python2.4/site-packages/ctypes/__init__.pyo
/usr/lib/python2.4/site-packages/ctypes/_endian.pyo
..............................
/usr/lib/python2.4/site-packages/ctypes/util.pyo
/usr/lib/python2.4/site-packages/ctypes/wintypes.pyo
RPM 제작 오류:
Installed (but unpackaged) file(s) found:
/usr/lib/python2.4/site-packages/ctypes/__init__.pyo
/usr/lib/python2.4/site-packages/ctypes/_endian.pyo
.............................
/usr/lib/python2.4/site-packages/ctypes/util.pyo
/usr/lib/python2.4/site-packages/ctypes/wintypes.pyo
error: command 'rpmbuild' failed with exit status 1
Provides: _ctypes.so _ctypes_test.so
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Requires: libc.so.6 libc.so.6(GLIBC_2.0) libc.so.6(GLIBC_2.1) libc.so.6(GLIBC_2.1.3) libc.so.6(GLIBC_2.3.4) libc.so.6(GLIBC_2.4) libpthread.so.0 python(abi) = 2.4 rtld(GNU_HASH)
파일 처리 중: ctypes-debuginfo-1.0.2-1
Provides: _ctypes.so.debug _ctypes_test.so.debug
Requires(rpmlib): rpmlib(CompressedFileNames) <= 3.0.4-1 rpmlib(PayloadFilesHavePrefix) <= 4.0-1
Checking for unpackaged file(s): /usr/lib/rpm/check-files /var/tmp/ctypes-1.0.2-1-buildroot
오류: Installed (but unpackaged) file(s) found:
/usr/lib/python2.4/site-packages/ctypes/__init__.pyo
/usr/lib/python2.4/site-packages/ctypes/_endian.pyo
..............................
/usr/lib/python2.4/site-packages/ctypes/util.pyo
/usr/lib/python2.4/site-packages/ctypes/wintypes.pyo
RPM 제작 오류:
Installed (but unpackaged) file(s) found:
/usr/lib/python2.4/site-packages/ctypes/__init__.pyo
/usr/lib/python2.4/site-packages/ctypes/_endian.pyo
.............................
/usr/lib/python2.4/site-packages/ctypes/util.pyo
/usr/lib/python2.4/site-packages/ctypes/wintypes.pyo
error: command 'rpmbuild' failed with exit status 1
우분투 10.4에서는 에러없이 생성된다.(이건 무슨 조화?)
포기할까 하다가 cx-Freeze 는 에러없이 RPM 패키지가 생성되는 것이다.
cx-Freeze 의 setup.py 를 분석하면 답이 있다.
먼저, 다음명령으로 라이브러리 빌드에는 문제가 없는지 확인한다.
여기서, 문제가 발생하는 건 각자 알아서 해결하자.(README 파일이나 홈페이지 참조)
python setup.py build
cx-Freeze 소스를 받아서 압축해제하고 setup.py 를 열어보면 다음 내용을 볼 수 있을 것이다.
......
import distutils.command.bdist_rpm
......
class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm):
# rpm automatically byte compiles all Python files in a package but we
# don't want that to happen for initscripts and samples so we tell it to
# ignore those files
def _make_spec_file(self):
specFile = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self)
specFile.insert(0, "%define _unpackaged_files_terminate_build 0%{nil}")
return specFile
def run(self):
distutils.command.bdist_rpm.bdist_rpm.run(self)
specFile = os.path.join(self.rpm_base, "SPECS",
"%s.spec" % self.distribution.get_name())
queryFormat = "%{name}-%{version}-%{release}.%{arch}.rpm"
command = "rpm -q --qf '%s' --specfile %s" % (queryFormat, specFile)
origFileName = os.popen(command).read()
parts = origFileName.split("-")
parts.insert(2, "py%s%s" % sys.version_info[:2])
newFileName = "-".join(parts)
self.move_file(os.path.join("dist", origFileName),
os.path.join("dist", newFileName))
......
commandClasses = dict(
build_ext = build_ext,
build_scripts = build_scripts,
bdist_rpm = bdist_rpm, # 여기
install = install,
install_packagedata = install_packagedata)
.....
setup(name = "cx_Freeze",
description = "create standalone executables from Python scripts",
long_description = "create standalone executables from Python scripts",
version = "4.2",
cmdclass = commandClasses, # 여기
options = dict(bdist_rpm = dict(doc_files = docFiles),
install = dict(optimize = 1)),
ext_modules = extensions,
packages = ['cx_Freeze'],
maintainer="Anthony Tuininga",
maintainer_email="anthony.tuininga@gmail.com",
url = "http://cx-freeze.sourceforge.net",
scripts = ["cxfreeze"],
classifiers = classifiers,
keywords = "freeze",
license = "Python Software Foundation License")
bdist_rpm 빌드명령을 커스터마이징하고 setup 에 등록해주면 되는 것이다.
다음은 ctypes 1.0.2 소스의 setup.py 를 수정한 부분이다.
........
print 'Installing data files to %s' % self.install_dir
install_data.install_data.finalize_options(self)
### 추가된 부분
import distutils.command.bdist_rpm
class bdist_rpm(distutils.command.bdist_rpm.bdist_rpm):
# rpm automatically byte compiles all Python files in a package but we
# don't want that to happen for initscripts and samples so we tell it to
# ignore those files
def _make_spec_file(self):
specFile = distutils.command.bdist_rpm.bdist_rpm._make_spec_file(self)
specFile.insert(0, "%define _unpackaged_files_terminate_build 0%{nil}")
return specFile
def run(self):
distutils.command.bdist_rpm.bdist_rpm.run(self)
specFile = os.path.join(self.rpm_base, "SPECS",
"%s.spec" % self.distribution.get_name())
queryFormat = "%{name}-%{version}-%{release}.%{arch}.rpm"
command = "rpm -q --qf '%s' --specfile %s" % (queryFormat, specFile)
origFileName = os.popen(command).read()
parts = origFileName.split("-")
parts.insert(2, "py%s%s" % sys.version_info[:2])
newFileName = "-".join(parts)
self.move_file(os.path.join("dist", origFileName),
os.path.join("dist", newFileName))
### 추가 끝부분
################################################################
# Specify the _ctypes extension
#
kw = {}
# common source files
kw["sources"] = ["source/_ctypes.c",
...........
url="http://starship.python.net/crew/theller/ctypes/",
platforms=["windows", "Linux", "MacOS X", "Solaris", "FreeBSD"],
download_url="http://sourceforge.net/project/showfiles.php?group_id=71702",
cmdclass = {'test': test, 'build_py': my_build_py, 'build_ext': my_build_ext,
'clean': my_clean, 'install_data': my_install_data,
'bdist_rpm': bdist_rpm #<< 여기
## 'ce_install_lib': ce_install_lib
},
)
## Local Variables:
## compile-command: "python setup.py build"
## End:
자, 다시 RPM 패키지를 만들어보자.
python setup.py bdist_rpm
마지막에 복사오류가 나지만 dist 폴더에 RPM 패키지가 생성되어있을 것이다.몇몇패키지들은 RPM 생성중 오류가 나지만 로그메시지를 잘 보면 해결할 수 있을 것이다.
(root 권한으로 수행(cofigobj?), MANIFEST 파일삭제(pymssql?),
setup.cfg 수정(mysql-python) 등등등)
위방법으로 Cython, MySQL-python, configobj, ctypes, hashlib, importlib, multiprocessing,
pymssql, pyodbc, subprocess32, unittest2 소스패키지에서 RPM 패키지를 생성해냈다.
2009년 11월 6일 금요일
윈도에서 GDB --tty 장치 연결하기..
gdb --tty=콘솔장치 옵션으로 표준입출력을 다른 콘솔장치에 연결할 수 있다.
그런데, 윈도에서는 어떻게 하지? /dev/tty, /dev/pty 이런 거 없는데..흠.
beverdbg 소스와 ollydbg 의 도움을 받아서 알아냈다.
결론을 말하면 윈도의 Named Pipe 를 이용하면 된다.
1. 다음의 파이썬 소스와 같이 Pipe 서버를 만든다.
2. 아래와 같이 GDB 를 실행한다.
3. GDB 에서 debugee(powerevt.exe) 을 run 명령을 수행한다.
그러면 다음과 같은 메시지가 보일것이다.
4. debugee 를 종료하면 표준출력을 Pipe Server 에서 보여줄것이다.
아직은 표준출력을 실시간으로 보여주지 못한다.
CreateNamedPipe 나 ReadFile 의 인자를 조금 조정해야 될듯하다.
5. GDB 가 Pipe 에 연결하지 못하면 run 명령시 다음과 같은 에러메시지가 보일것이다.
그런데, 윈도에서는 어떻게 하지? /dev/tty, /dev/pty 이런 거 없는데..흠.
beverdbg 소스와 ollydbg 의 도움을 받아서 알아냈다.
결론을 말하면 윈도의 Named Pipe 를 이용하면 된다.
1. 다음의 파이썬 소스와 같이 Pipe 서버를 만든다.
import time
import pywintypes
import win32file
import win32pipe
import winerror
PIPE_NAME = r"\\.\pipe\marungdb1234"
FILE_FLAG_OVERLAPPED = 0x40000000
def PipeMainThread():
print PIPE_NAME
PipeHandle = None
while 1:
if not PipeHandle:
try:
PipeHandle = win32pipe.CreateNamedPipe(PIPE_NAME,
win32pipe.PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
win32pipe.PIPE_TYPE_MESSAGE,
win32pipe.PIPE_UNLIMITED_INSTANCES,
0, 0, 3000, None)
except pywintypes.error, msg:
print msg
print msg[2]
PipeHandle = None
else:
print "Pipe Create"
if PipeHandle:
try:
hr, Str = win32file.ReadFile(PipeHandle, 4096, None)
except pywintypes.error, msg:
if msg[0] == winerror.ERROR_PIPE_LISTENING:
time.sleep(0.01)
#elif msg[0] == winerror.ERROR_BROKEN_PIPE:
# print msg
# print msg[2]
# Loop = False
else:
win32file.CloseHandle(PipeHandle)
PipeHandle = None
else:
#print hr
print Str
#self.LogSync(Str)
if PipeHandle:
win32file.CloseHandle(PipeHandle)
if __name__ == "__main__":
PipeMainThread()
2. 아래와 같이 GDB 를 실행한다.
gdb --tty=\\.\pipe\marungdb1234 powerevt.exe
3. GDB 에서 debugee(powerevt.exe) 을 run 명령을 수행한다.
그러면 다음과 같은 메시지가 보일것이다.
(gdb) run
Starting program: D:\myprj\marungdb/powerevt.exe
[New Thread 3012.0x844]
Starting program: D:\myprj\marungdb/powerevt.exe
[New Thread 3012.0x844]
4. debugee 를 종료하면 표준출력을 Pipe Server 에서 보여줄것이다.
아직은 표준출력을 실시간으로 보여주지 못한다.
CreateNamedPipe 나 ReadFile 의 인자를 조금 조정해야 될듯하다.
5. GDB 가 Pipe 에 연결하지 못하면 run 명령시 다음과 같은 에러메시지가 보일것이다.
(gdb) run
Starting program: D:\myprj\marungdb/powerevt.exe
warning: Warning: Failed to open TTY \\.\pipe\marungdb1234, error 0x2.
[New Thread 1488.0x3b4]
Starting program: D:\myprj\marungdb/powerevt.exe
warning: Warning: Failed to open TTY \\.\pipe\marungdb1234, error 0x2.
[New Thread 1488.0x3b4]
2009년 11월 5일 목요일
MultiThreaded XMLRPCServer
http://mail.python.org/pipermail/python-list/2007-March/604533.html
윗 글을 참조하여 만들었음.
윗 글을 참조하여 만들었음.
from SocketServer import ThreadingMixIn
from SimpleXMLRPCServer import *
import time
class TestRequestHandler(SimpleXMLRPCRequestHandler):
def _dispatch(self, method, params):
try:
server_method = getattr(self, "do_"+method)
except:
raise AttributeError, "No XML-RPC procedure do_%s" % method
return server_method(*params)
def log_message(self, format, *args):
print format % args
def do_incr(self, k):
return k+1
def do_incr_delay(self, k):
time.sleep(10)
return k+1
class ThreadedXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
""""My Threaded XMLRPC Server"""
if __name__ == "__main__":
#server = SimpleXMLRPCServer(('', 8000), TestRequestHandler)
server = ThreadedXMLRPCServer(('', 8000), TestRequestHandler)
server.serve_forever()
DrMingw II - 윈도용 JIT 디버거
blogspot 에 있던 거 옮겨옴.
-------------------------
DrMingw I - 윈도용 JIT 디버거 의 경우 DrMingw.exe 를 JIT 로 등록해야되는 불편함있다.
그래서, 에러발생시 DrMingw.exe 를 프로그램에서 JIT로 호출되게 하는 방법을 알아보자.
역시, mingw-utils 의 exchndl.dll 이 필요하다.
방법은 무척간단하다. 프로그램 시작부분에서 exchndl.dll 를 로드해주면 된다.
다음 소스를 컴파일해보자. - 이전과 같이 디버깅정보를 포함하자~
컴파일한 실행파일을 실행하면 "응용프로그램 오류" 창이 나오는데 "확인" 버튼을 누르자.
"취소"버튼을 눌러도 되지만 등록된 JIT 디버거가 제대로 동작하지 않는 것 같다.
그러면, 실행파일과 같은 이름의 RPT 파일이 생성된다.
내용은 아래와 비슷하다.
XP 상에서 Mingw, VC6.0 에서 테스트했다.
-------------------------
DrMingw I - 윈도용 JIT 디버거 의 경우 DrMingw.exe 를 JIT 로 등록해야되는 불편함있다.
그래서, 에러발생시 DrMingw.exe 를 프로그램에서 JIT로 호출되게 하는 방법을 알아보자.
역시, mingw-utils 의 exchndl.dll 이 필요하다.
방법은 무척간단하다. 프로그램 시작부분에서 exchndl.dll 를 로드해주면 된다.
다음 소스를 컴파일해보자. - 이전과 같이 디버깅정보를 포함하자~
#include <tchar.h>
#include <windows.h>
#include <stdio.h>
int _tmain(int argc, TCHAR *argv[])
{
int *Ptr=(int *)0x00000;
HMODULE hModDbg;
if( ( hModDbg = LoadLibrary(_T("exchndl.dll")) ) == NULL )
{
_tprintf(_T("LoadLibrary Error\n"));
}
*Ptr = 0;
if( hModDbg )
{
FreeLibrary(hModDbg);
}
return 0;
}
컴파일한 실행파일을 실행하면 "응용프로그램 오류" 창이 나오는데 "확인" 버튼을 누르자.
"취소"버튼을 눌러도 되지만 등록된 JIT 디버거가 제대로 동작하지 않는 것 같다.
그러면, 실행파일과 같은 이름의 RPT 파일이 생성된다.
내용은 아래와 비슷하다.
Error occured on Thursday, March 5, 2009 at 12:12:53.
D:\prj\secu\JitDbgTest\test_except.exe caused an Access Violation at location 00401360 in module D:\prj\secu\JitDbgTest\test_except.exe Writing to location 00000000.
Registers:
eax=00000000 ebx=7ffff000 ecx=77bf18bf edx=77c11b78 esi=01c99d40 edi=2be5cf9e
eip=00401360 esp=0022ff50 ebp=0022ff78 iopl=0 nv up ei ng nz ac po nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010296
Call stack:
00401360 D:\prj\secu\JitDbgTest\test_except.exe:00401360 main D:/prj/secu/JitDbgTest/test_except.c:22
0040124B D:\prj\secu\JitDbgTest\test_except.exe:0040124B
00401298 D:\prj\secu\JitDbgTest\test_except.exe:00401298
7C817067 C:\WINDOWS\system32\kernel32.dll:7C817067 RegisterWaitForInputIdle
D:\prj\secu\JitDbgTest\test_except.exe caused an Access Violation at location 00401360 in module D:\prj\secu\JitDbgTest\test_except.exe Writing to location 00000000.
Registers:
eax=00000000 ebx=7ffff000 ecx=77bf18bf edx=77c11b78 esi=01c99d40 edi=2be5cf9e
eip=00401360 esp=0022ff50 ebp=0022ff78 iopl=0 nv up ei ng nz ac po nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010296
Call stack:
00401360 D:\prj\secu\JitDbgTest\test_except.exe:00401360 main D:/prj/secu/JitDbgTest/test_except.c:22
0040124B D:\prj\secu\JitDbgTest\test_except.exe:0040124B
00401298 D:\prj\secu\JitDbgTest\test_except.exe:00401298
7C817067 C:\WINDOWS\system32\kernel32.dll:7C817067 RegisterWaitForInputIdle
XP 상에서 Mingw, VC6.0 에서 테스트했다.
피드 구독하기:
글 (Atom)