我建了一個服務器使用Windows命名管道,使用下面的關鍵代碼:
def run(self):
# This is the main server loop for the Win32 platform
import win32pipe
import win32file
self.pipeHandle = win32pipe.CreateNamedPipe(
'\\\\.\\pipe\\myapp_requests',
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_BYTE |
win32pipe.PIPE_READMODE_BYTE |
win32pipe.PIPE_WAIT,
1,
4096,
4096,
10000,
None)
if self.pipeHandle == win32file.INVALID_HANDLE_VALUE:
print 'Failed to create named pipe %s!' % self.pipeName
print 'Exiting...'
sys.exit(1)
while True:
# Open file connection
win32pipe.ConnectNamedPipe(self.pipeHandle)
# Run the main message loop until it exits, usually because
# of a loss of communication on the pipe
try:
self.messageLoop()
except ServerKillSignal:
break
# Return the pipes to their disconnected condition and try again
try: win32pipe.DisconnectNamedPipe(self.pipeHandle)
except: pass
win32file.CloseHandle(self.pipeHandle)
print "Exiting server"
的方法messageLoop()
從管道中讀取數據,使用win32file.ReadFile()
,直到win32file.error被拋出。然後它退出,允許run()重新啓動它。
在我的實現中,用戶不太可能擁有管理員訪問權限,因此這不能作爲系統服務啓動。相反,我編寫客戶端來檢查'\。\ pipe \ pyccf_requests'中是否存在管道。如果它不存在,那麼客戶端啓動一個新的服務器進程。
你看過logging.handlers.SocketHandler:http://docs.python.org/library/logging#sending-and-receiving-logging-events-across-a-network?它至少包含了你爲你描述的部分內容,並且是標準庫的一部分。 – 2010-05-18 00:08:22
@丹這看起來很有用,你應該把它寫成答案。 ;) – Ipsquiggle 2010-05-18 00:26:44