Python进程间通信之命名管道(Windows)

前面文章说了一下 Linux 命名管道的实现,今天看看 Windows 上我们怎么实现。

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

  • win32pipe.CreateNamedPipe()
  • win32pipe.ConnectNamedPipe()
  • win32file.ReadFile()
  • win32file.WriteFile()

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

server.py

import win32file
import win32pipe

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

while True:
    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:
        while True:
            try:
                win32pipe.ConnectNamedPipe(named_pipe, None)
                data = win32file.ReadFile(named_pipe, PIPE_BUFFER_SIZE, None)

                if data is None or len(data) < 2:
                    continue

                print 'receive msg:', data
            except BaseException as e:
                print "exception:", e
                break
    finally:
        try:
            win32pipe.DisconnectNamedPipe(named_pipe)
        except:
            pass

client.py

import win32pipe, win32file
import time

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:
    for i in range(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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容