BrokenPipeError when writing to sys.stdout and a Linux pipe

Viewed 31

I want to write to sys.stdout in a way that the output can be 'piped' in Linux (e.g. with | head). I thought I was being clever with the following code: by specifying sys.stdout as the file, I can let my program write to STDOUT or a file depending on the input flag.

def write(outfile: str, data: str):
    try:
        fp = sys.stdout  # already an open descriptor
        if outfile:  # user wants to write to file
            fp = open(outfile, "w+")
            
        fp.write(data)
    except Exception as e:
        print("Could not write to file", e)

This works fine. However, when I decide to run the command with a pipe:

python3 command.py | head

I get a BrokenPipeError. Why is this?

0 Answers
Related