将管道放入字典

put a pipe in a dictionary

PMU_PIPE_MAP = {}

PIPE= 'tmp/%s.pipe' % hostname
if not os.path.exists(PIPE):
    os.mkfifo(PIPE)

PMU_PIPE_MAP[hostname] = os.open(PIPE, os.O_WRONLY)

我正在尝试打开 n 管道。为了跟踪它们,我想以某种方式存储它们——就像在字典中——我认为上面的代码应该可以工作,但它在执行过程中冻结了。有什么建议吗?

但这确实有效:

pipein = os.open(PIPE, os.O_WRONLY)

未经测试,但可能会对您有所帮助

import os, tempfile

tmpdir = tempfile.mkdtemp()

PMU_FIFO_MAP = {}

def openFIFO(pname):
    filename = os.path.join(tmpdir, '%s' % pname)
    fifo = None
    try:
        os.mkfifo(filename)
        fifo = os.open(PIPE, os.O_WRONLY)
    except OSError, e:
        print "Failed to create FIFO: %s" % e
        print e.printStackTrace()
    return fifo

def closeFIFO(fname, fifo):
    fifo.close()
    os.remove(fname)

for hostname in hostnames:
    fifo = openFIFO(hostname)
    if fifo:
        PMU_FIFO_MAP[hostname] = fifo

# do stuff with fifos

for fname, fifo in PMU_FIFO_MAP.items():
    closeFIFO(fname, fifo)
    del PMU_FIFO_MAP[hostname]

os.rmdir(tmpdir)

另见可能 Create a temporary FIFO (named pipe) in Python?

啊哈!显然,在我们从管道中获得 return 之前,必须在另一端进行读取。所以我问的问题是不正确的,因为我没有以同样的方式测试这两个场景。所以我的问题是理解管道是如何工作的。在这种情况下,一旦在 'read' 端打开管道,字典条目就会成功,但在此之前会阻塞。 how to determine if pipe can be written