diff --git a/flake8_mypy.py b/flake8_mypy.py index 5560f2b..0577ec6 100644 --- a/flake8_mypy.py +++ b/flake8_mypy.py @@ -183,15 +183,26 @@ def run(self) -> Iterator[_Flake8Error]: # Always put the file in a separate temporary directory to avoid # unexpected clashes with other .py and .pyi files in the same original # directory. - with TemporaryDirectory(prefix='flake8mypy_') as d: - with NamedTemporaryFile( - 'w', encoding='utf8', prefix='tmpmypy_', suffix='.py', dir=d - ) as f: - self.filename = f.name - for line in self.lines: - f.write(line) - f.flush() - yield from self._run() + try: + with TemporaryDirectory(prefix='flake8mypy_') as d: + with NamedTemporaryFile( + 'wt', prefix='tmpmypy_', suffix='.py', dir=d + ) as f: + self.filename = f.name + for line in self.lines: + f.write(line) + f.flush() + yield from self._run() + except UnicodeEncodeError: + with TemporaryDirectory(prefix='flake8mypy_') as d: + with NamedTemporaryFile( + 'wb', prefix='tmpmypy_', suffix='.py', dir=d + ) as f: + self.filename = f.name + for line in self.lines: + f.write(line.encode(r'utf8')) + f.flush() + yield from self._run() def _run(self) -> Iterator[_Flake8Error]: mypy_cmdline = self.build_mypy_cmdline(self.filename, self.options.mypy_config)