Skip to content

Run mypy programmatically on entire files (was #2369) #10810

Closed
@edreamleo

Description

@edreamleo

Documentation

mypy issue #2369 was closed because, indeed, it does not make sense to run mypy on code fragments.

However, it does make sense for an IDE such as Leo to run mypy programmatically on entire files. This is far from easy, at least on Windows. For example, supposing that a mypy.bat file exists, one can not simply use subprocess.Popen to run mypy.bat. Somehow the output from mypy.bat will be swallowed. Instead, it looks like subprocess.run is required.

The following tested script finds and runs python/scripts/mypy.exe and captures the result. As you can see, the script is immune from changes to mypy's internal API. Small changes will be needed on linux, MacOS.

import os
import subprocess
import sys
#
# Change directory as needed.
directory = # <path to program under test, in this case, launchLeo.py>
os.chdir(directory)
#
# Compute path to Python/Scripts/mypy.exe.
python_dir = os.path.dirname(sys.executable)
scripts_dir = os.path.join(python_dir, 'Scripts')
mypy_exe = os.path.join(scripts_dir, 'mypy.exe')
#
# Run mypy.exe with arguments.
command = [
    mypy_exe,
    '--disable-error-code=attr-defined',
    'launchLeo.py'
]
result = subprocess.run(command, capture_output=True, universal_newlines=True)
#
# Handle the output.
for line in result.stdout.splitlines(True):
    print(line.rstrip())

It should be possible to use this script to run mypy on directories.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions