Create a temporary FIFO (named pipe) in Python?

后端 未结 6 1301
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 05:49

How can you create a temporary FIFO (named pipe) in Python? This should work:

import tempfile

temp_file_name = mktemp()
os.mkfifo(temp_file_name)
open(temp_         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 06:38

    Effectively, all that mkstemp does is run mktemp in a loop and keeps attempting to exclusively create until it succeeds (see stdlib source code here). You can do the same with os.mkfifo:

    import os, errno, tempfile
    
    def mkftemp(*args, **kwargs):
        for attempt in xrange(1024):
            tpath = tempfile.mktemp(*args, **kwargs)
    
            try:
                os.mkfifo(tpath, 0600)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    # lets try again
                    continue
                else:
                    raise
            else:
               # NOTE: we only return the path because opening with
               # os.open here would block indefinitely since there 
               # isn't anyone on the other end of the fifo.
               return tpath
        else:
            raise IOError(errno.EEXIST, "No usable temporary file name found")
    

提交回复
热议问题