Skip to content

mimetypes CLI writes error messages to stdout instead of stderr #149682

@htjworld

Description

@htjworld

Description

The mimetypes command-line interface documentation states:

For each type entry, the script writes a line into the standard output stream. If an unknown type occurs, it writes an error message into the standard error stream and exits with the return code 1.

However, the actual implementation writes all output — including error messages — to stdout via a single print() call:

# Lib/mimetypes.py
if __name__ == '__main__':
    import sys
    results = _main()
    print("\n".join(results))  # errors and normal output mixed into stdout
    sys.exit(any(result.startswith("error: ") for result in results))

Verified behavior:

$ python -m mimetypes foo.unknownext > out.txt 2> err.txt
$ cat out.txt
error: media type unknown for foo.unknownext
$ cat err.txt
(empty)

Error messages go to stdout, stderr is empty — contradicting the docs.

Additional issue: stale docs example

The documentation example shows:

$ python -m mimetypes filename.pict
error: unknown extension of filename.pict

But filename.pict is now recognized:

$ python -m mimetypes filename.pict
type: image/pict encoding: None

The example error message format also doesn't match the actual output ("error: unknown extension of..." vs "error: media type unknown for...").

Proposed fix

Route error messages to stderr in the __main__ block:

if __name__ == '__main__':
    import sys
    results = _main()
    has_error = False
    for result in results:
        if result.startswith("error: "):
            print(result, file=sys.stderr)
            has_error = True
        else:
            print(result)
    sys.exit(has_error)

And update the docs example to use a genuinely unrecognized extension.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions