Is it possible to call Pyright from code (as an API)?

196 views Asked by At

It seems that Pyright (the Python type checker made by Microsoft) can only be used as a command line tool or from VS Code. But is it possible to call pyright from code (as an API)?

For example, mypy supports usage like:

import sys
from mypy import api

result = api.run("your code")
2

There are 2 answers

0
willwrighteng On BEST ANSWER

like @Grismar said, this might be an xy problem... if not, here is a general solution:

import subprocess

command = ['pyright', 'path/to/your/file.py']
result = subprocess.run(command, capture_output=True, text=True)
output = result.stdout

print(output)
1
Mahdi Salehi On

also you can use this solution:

import subprocess


try:
    command = ['pyright', 'path/to/your/file.py']
    result = subprocess.run(command, capture_output=True, text=True, shell=True)
    if result.returncode !=0:
        print(f'Return Code Not Zero : {result.returncode}')
        print(f'Stderror : {result.stderr}')
    output = result.stdout
    print(f'Stdout :{output}')
except subprocess.CalledProcessError as e:
    print(f"[CalledProcessError]: {e}")
except FileNotFoundError as e:
    print(f"[FileNotFoundError]: {e}")
except Exception as e:
    print(f"[Other error occurred]: {e}")