Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo và dùng named pipe (FIFO) trong Python?


FIFO là pipe truy cập như file thông thường. FIFO tồn tại cho đến khi xóa (ví dụ os.unlink()). Thường dùng làm rendezvous giữa process "client" và "server": server mở FIFO đọc, client mở ghi. Lưu ý mkfifo() không mở FIFO — chỉ tạo rendezvous point. Để tạo FIFO và dùng trong Python, dùng os.mkfifo(). Nhưng mkfifo fail với exception File exists nếu file đã tồn tại. Tránh bằng try-except.

Ví dụ

import os, sys
# Path tạo
path = "/tmp/hourly"
try:
    os.mkfifo(path)
except OSError as e:
    print("Failed to create FIFO: %s" % e)
else:
    fifo = open(path, 'w')
    print("Path is created")

Chạy chương trình, pipe sẽ được tạo.