473,396 Members | 1,671 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Example Code - Named Pipes (Python 2.4 + ctypes on Windows)

Hello,
Here is an example of Multithreaded Pipe Server and Client using the
excellent ctypes library (Windows).

Reference - MSDN:
http://msdn.microsoft.com/library/de...ipe_server.asp
and
http://msdn.microsoft.com/library/de...ipe_client.asp

Best Regards,
Srijit

Named Pipe Server Source Code:

from ctypes import *

PIPE_ACCESS_DUPLEX = 0x3
PIPE_TYPE_MESSAGE = 0x4
PIPE_READMODE_MESSAGE = 0x2
PIPE_WAIT = 0
PIPE_UNLIMITED_INSTANCES = 255
BUFSIZE = 4096
NMPWAIT_USE_DEFAULT_WAIT = 0
INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535

MESSAGE = "Default answer from server\0"
szPipename = "\\\\.\\pipe\\mynamedpipe"
def ReadWrite_ClientPipe_Thread(hPipe):
chBuf = create_string_buffer(BUFSIZE)
cbRead = c_ulong(0)
while 1:
fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
byref(cbRead), None)
if ((fSuccess ==1) or (cbRead.value != 0)):
print chBuf.value
cbWritten = c_ulong(0)
fSuccess = windll.kernel32.WriteFile(hPipe,
c_char_p(MESSAGE),
len(MESSAGE),
byref(cbWritten),
None
)
else:
break
if ( (not fSuccess) or (len(MESSAGE) != cbWritten.value)):
print "Could not reply to the client's request from the
pipe"
break
else:
print "Number of bytes written:", cbWritten.value

windll.kernel32.FlushFileBuffers(hPipe)
windll.kernel32.DisconnectNamedPipe(hPipe)
windll.kernel32.CloseHandle(hPipe)
return 0

def main():
THREADFUNC = CFUNCTYPE(c_int, c_int)
thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
while 1:
hPipe = windll.kernel32.CreateNamedPipeA(szPipename,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE |
PIPE_READMODE_MESSAGE
|
PIPE_WAIT,

PIPE_UNLIMITED_INSTANCES,
BUFSIZE, BUFSIZE,

NMPWAIT_USE_DEFAULT_WAIT,
None
)
if (hPipe == INVALID_HANDLE_VALUE):
print "Error in creating Named Pipe"
return 0

fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
if ((fConnected == 0) and (windll.kernel32.GetLastError() ==
ERROR_PIPE_CONNECTED)):
fConnected = 1
if (fConnected == 1):
dwThreadId = c_ulong(0)
hThread = windll.kernel32.CreateThread(None, 0,
thread_func, hPipe, 0, byref(dwThreadId))
if (hThread == -1):
print "Create Thread failed"
return 0
else:
windll.kernel32.CloseHandle(hThread)
else:
print "Could not connect to the Named Pipe"
windll.kernel32.CloseHandle(hPipe)
return 0
if __name__ == "__main__":
main()

Named Pipe Client Source Code:

from ctypes import *

GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
OPEN_EXISTING = 0x3
INVALID_HANDLE_VALUE = -1
PIPE_READMODE_MESSAGE = 0x2
ERROR_PIPE_BUSY = 231
ERROR_MORE_DATA = 234
BUFSIZE = 512

MESSAGE = "Default message from client\0"
szPipename = "\\\\.\\pipe\\mynamedpipe"

def main():
while 1:
hPipe = windll.kernel32.CreateFileA(szPipename, GENERIC_READ |
GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None)
if (hPipe != INVALID_HANDLE_VALUE):
break
else:
print "Invalid Handle Value"
if (windll.kernel32.GetLastError() != ERROR_PIPE_BUSY):
print "Could not open pipe"
return
elif ((windll.kernel32.WaitNamedPipeA(szPipename, 20000)) ==
0):
print "Could not open pipe\n"
return
dwMode = c_ulong(PIPE_READMODE_MESSAGE)
fSuccess = windll.kernel32.SetNamedPipeHandleState(hPipe,
byref(dwMode), None, None);
if (not fSuccess):
print "SetNamedPipeHandleState failed"
cbWritten = c_ulong(0)
fSuccess = windll.kernel32.WriteFile(hPipe, c_char_p(MESSAGE),
len(MESSAGE), byref(cbWritten), None)
if ((not fSuccess) or (len(MESSAGE) != cbWritten.value)):
print "Write File failed"
return
else:
print "Number of bytes written:", cbWritten.value

fSuccess = 0
chBuf = create_string_buffer(BUFSIZE)
cbRead = c_ulong(0)
while (not fSuccess): # repeat loop if ERROR_MORE_DATA
fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
byref(cbRead), None)
if (fSuccess == 1):
print "Number of bytes read:", cbRead.value
print chBuf.value
break
elif (windll.kernel32.GetLastError() != ERROR_MORE_DATA):
break

windll.kernel32.CloseHandle(hPipe)
return
if __name__ == "__main__":
main()

Jul 18 '05 #1
6 10713

Srijit Kumar Bhadra wrote:
Hello,
Here is an example of Multithreaded Pipe Server and Client using the
excellent ctypes library (Windows).


Coincidentally, the other day I just used named pipes in for the first
time. I recommend using the excellent win32api extension; I believe it
is included by deafult in the ActiveState distro.

The API calls look fairly similar, but you pass strings instead of
c_whatever_p(), they return tuples, and they throw exceptions instead
of returning HRESULT h s.t. FAILED(h). The resulting code feels much
more Pythonic. For example, my first test looked like this:

def testread(self):
"""Read all data currently in pipe."""
while True:
try:
(nRead, nAvail, nMessage) =
win32pipe.PeekNamedPipe(self.hFile, 0)
if nAvail:
(hr, data) = win32file.ReadFile(self.hFile, nAvail)
return data
except pywintypes.error, e:
errno = e.args[0]
if errno == 109: # other end disconnected
self.disconnect()
self.connect()
else:
raise

It's kind of cool that you can directly port C code to Python, but the
end result is IMO nigh-unreadable.

p

Jul 18 '05 #2
Hello,
I am quite familiar with Mark Hammond's win32all. It is excellent.
However, I wish that there was more documentation of win32all beyond
existing PyWin32.chm. I am aware of "Python Programming on Win32" but I
do not have access to it at present.

Best Regards,
/Srijit

Jul 18 '05 #3
"Srijit Kumar Bhadra" <sr****@yahoo.com> wrote in
Here is an example of Multithreaded Pipe Server and Client using the
excellent ctypes library (Windows).


Excellent. Maybe you would also like to post it to the

http://starship.python.net/crew/thel...i/CtypesModule

Ctypes-Wiki for easier reference?

best regards,

Harald
Jul 18 '05 #4
"Srijit Kumar Bhadra" <sr****@yahoo.com> writes:
Hello,
I am quite familiar with Mark Hammond's win32all. It is excellent.
However, I wish that there was more documentation of win32all beyond
existing PyWin32.chm. I am aware of "Python Programming on Win32" but I
do not have access to it at present.


At least one chapter of PPW32 is available as sample chapter somewhere
on an OReilly site - but you should buy the book anyway imo. For the
windows api functions you should refer to Microsoft's docs at MSDN.

Thomas
Jul 18 '05 #5
Harald Massa <cp*********@spamgourmet.com> writes:
"Srijit Kumar Bhadra" <sr****@yahoo.com> wrote in
Here is an example of Multithreaded Pipe Server and Client using the
excellent ctypes library (Windows).


Excellent. Maybe you would also like to post it to the

http://starship.python.net/crew/thel...i/CtypesModule

Ctypes-Wiki for easier reference?


Or the activestate Python cookbook.

Thonas
Jul 18 '05 #6
Srijit Kumar Bhadra wrote:
However, I wish that there was more documentation of win32all beyond
existing PyWin32.chm.


I suspect you have already used the "more documentation" -- it's the
MSDN docs.

p

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Srijit Kumar Bhadra | last post by:
Hello, Here are code snippets to create and access shared memory in Python with and without ctypes module. With regards, Srijit Filename : SharedMemCreate.py import msvcrt, mmap
5
by: glenn.owens | last post by:
In the process of doing some routine monitoring/clean-up we've discovered that several (many?) users are apparently set to access our SQL Server 2000 database instances via the Named Pipes...
2
by: Rudolf Bargholz | last post by:
Hi, DB2 7.1 FP11 Windows 2000 Earlier this evening, after dropping and recreating a trigger, DB2 locked up. I am not entirely sure that the cause of the problem was the replacing of the...
4
by: Ken Allen | last post by:
Is there any built-in facility for handling named pipes in C#/.Net, or must one use unsafe code to access the WIN32 API directly? There exists some code that uses named pipes heavily and there...
1
by: motimh | last post by:
I am trying to use named pipes to interprocess communication. My concern is the cpu wait time between them. Can someone show me the code to do this in VBNet? Is there an event that can be...
4
by: Noralf Trønnes | last post by:
Hi I'm trying to use a DLL from Python using ctypes. The call to dso_lib.capture_hold_chk() does return 232. So it seem to work. The call to dso_lib.port_init(init_data) gives: WindowsError:...
4
by: est | last post by:
Hi all I am trying to port Scribes to Windows, but I could not find a package named dbus-python for windows. There is a windbus <http:// sourceforge.net/projects/windbus/but it not for Python,...
7
by: andrewb | last post by:
Hi all, Having some trouble using named pipes and Visual Basic .NET and would appreciate and help you could offer. Essentially I am trying to develop a simple client/server application that...
0
by: allynm | last post by:
Hello everyone, I am trying to network over a small wireless LAN a Windows 7 box and a Windows XP (SP3) box. I have written an application that uses Windows named pipes. The code appears to be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.