Create a temporary FIFO (named pipe) in Python?

后端 未结 6 1300
被撕碎了的回忆
被撕碎了的回忆 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:24

    You may find it handy to use the following context manager, which creates and removes the temporary file for you:

    import os
    import tempfile
    from contextlib import contextmanager
    
    
    @contextmanager
    def temp_fifo():
        """Context Manager for creating named pipes with temporary names."""
        tmpdir = tempfile.mkdtemp()
        filename = os.path.join(tmpdir, 'fifo')  # Temporary filename
        os.mkfifo(filename)  # Create FIFO
        try:
            yield filename
        finally:
            os.unlink(filename)  # Remove file
            os.rmdir(tmpdir)  # Remove directory
    

    You can use it, for example, like this:

    with temp_fifo() as fifo_file:
        # Pass the fifo_file filename e.g. to some other process to read from.
        # Write something to the pipe 
        with open(fifo_file, 'w') as f:
            f.write("Hello\n")
    

提交回复
热议问题