1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python命名管道通讯_Python进程间通信的命名管道详解(Windows)

python命名管道通讯_Python进程间通信的命名管道详解(Windows)

时间:2020-03-10 08:19:00

相关推荐

python命名管道通讯_Python进程间通信的命名管道详解(Windows)

本文和大家分享的主要是windows系统下,python进程间通信的命名管道相关内容 ,一起来看看吧,希望对大家学习python有所帮助。

在Windows上的命名管道主要是通过调用win32 api的以下方法来实现的:

- win32pipe.CreateNamedPipe()

- win32pipe.ConnectNamedPipe()

- win32file.ReadFile()

- win32file.WriteFile()

下面看一个例子,比较简单,只是需要注意一下命名管道的命名规则。

server.py

importwin32fileimportwin32pipe

PIPE_NAME = r'\\\\.\\pipe\\test_pipe'

PIPE_BUFFER_SIZE = 65535

whileTrue:

named_pipe = win32pipe.CreateNamedPipe(PIPE_NAME,

win32pipe.PIPE_ACCESS_DUPLEX,

win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT | win32pipe.PIPE_READMODE_MESSAGE,

win32pipe.PIPE_UNLIMITED_INSTANCES,

PIPE_BUFFER_SIZE,

PIPE_BUFFER_SIZE, 500,None)

try:

whileTrue:

try:

win32pipe.ConnectNamedPipe(named_pipe,None)

data = win32file.ReadFile(named_pipe, PIPE_BUFFER_SIZE,None)

ifdataisNoneorlen(data) < 2:

continue

print'receive msg:', data

exceptBaseExceptionase:

print"exception:", e

break

finally:

try:

win32pipe.DisconnectNamedPipe(named_pipe)

except:

pass

client.py

importwin32pipe, win32fileimporttime

PIPE_NAME = r'\\\\.\\pipe\\test_pipe'

file_handle = win32file.CreateFile(PIPE_NAME,

win32file.GENERIC_READ | win32file.GENERIC_WRITE,

win32file.FILE_SHARE_WRITE,None,

win32file.OPEN_EXISTING, 0,None)try:

foriinrange(1, 11):

msg = str(i)

print'send msg:', msg

win32file.WriteFile(file_handle, msg)

time.sleep(1)finally:

try:

win32file.CloseHandle(file_handle)

except:

pass

测试

.首先运行server.py

.然后运行client.py

来源:kongxx的专栏

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。