Skip to content

flake8 fails if sys.stdout is an io.StringIO object #1419

@eerovaher

Description

@eerovaher

Please describe how you installed Flake8

$ pip install flake8
The exact, unmodified output of `flake8 --bug-report` (click this line to show)

{
"dependencies": [],
"platform": {
"python_implementation": "CPython",
"python_version": "3.8.10",
"system": "Linux"
},
"plugins": [
{
"is_local": false,
"plugin": "mccabe",
"version": "0.6.1"
},
{
"is_local": false,
"plugin": "pycodestyle",
"version": "2.8.0"
},
{
"is_local": false,
"plugin": "pyflakes",
"version": "2.4.0"
}
],
"version": "4.0.1"
}

Please describe the problem or feature

There seems to be a problem with this line:

sys.stdout.buffer.write(output.encode() + self.newline.encode())

The Python documentation (https://docs.python.org/3.8/library/sys.html#sys.stdout) warns that sys.stdout might end up being an io.StringIO object, which does not have a buffer attribute, and I have found a case where this happens in practice.

If this is a bug report, please explain with examples (and example code) what you expected to happen and what actually happened.

I wanted to use pycodestyle_magic together with flake8 in a Jupyter notebook. So the first code cell is:

%load_ext pycodestyle_magic
%flake8_on

and the second:

print( 0)

The result is:

AttributeError: '_io.StringIO' object has no attribute 'buffer'

I replaced the previously mentioned line 187 with the following four lines:

            try:
                sys.stdout.buffer.write(output.encode() + self.newline.encode())
            except AttributeError:
                print(output, end=self.newline)

and that fixed the problem for me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions