|
| 1 | +"""This module makes it possible to use mypy as part of a Python application. |
| 2 | +
|
| 3 | +Since mypy still changes, the API was kept utterly simple and non-intrusive. |
| 4 | +It just mimics command line activation without starting a new interpreter. |
| 5 | +So the normal docs about the mypy command line apply. |
| 6 | +Changes in the command line version of mypy will be immediately useable. |
| 7 | +
|
| 8 | +Just import this module and then call the 'run' function with exactly the |
| 9 | +string you would have passed to mypy from the command line. |
| 10 | +Function 'run' returns a tuple of strings: (<normal_report>, <error_report>), |
| 11 | +in which <normal_report> is what mypy normally writes to sys.stdout and |
| 12 | +<error_report> is what mypy normally writes to sys.stderr. |
| 13 | +Any pretty formatting is left to the caller. |
| 14 | +
|
| 15 | +Trivial example of code using this module: |
| 16 | +
|
| 17 | +import sys |
| 18 | +from mypy import api |
| 19 | +
|
| 20 | +result = api.run(' '.join(sys.argv[1:])) |
| 21 | +
|
| 22 | +if result[0]: |
| 23 | + print('\nType checking report:\n') |
| 24 | + print(result[0]) # stdout |
| 25 | +
|
| 26 | +if result[1]: |
| 27 | + print('\nError report:\n') |
| 28 | + print(result[1]) # stderr |
| 29 | +""" |
| 30 | + |
| 31 | +import sys |
| 32 | +from io import StringIO |
| 33 | +from typing import Tuple |
| 34 | +from mypy.main import main |
| 35 | + |
| 36 | + |
| 37 | +def run(params: str) -> Tuple[str, str]: |
| 38 | + sys.argv = [''] + params.split() |
| 39 | + |
| 40 | + old_stdout = sys.stdout |
| 41 | + new_stdout = StringIO() |
| 42 | + sys.stdout = new_stdout |
| 43 | + |
| 44 | + old_stderr = sys.stderr |
| 45 | + new_stderr = StringIO() |
| 46 | + sys.stderr = new_stderr |
| 47 | + |
| 48 | + try: |
| 49 | + main(None) |
| 50 | + except: |
| 51 | + pass |
| 52 | + |
| 53 | + sys.stdout = old_stdout |
| 54 | + sys.stderr = old_stderr |
| 55 | + |
| 56 | + return new_stdout.getvalue(), new_stderr.getvalue() |
0 commit comments