Coder Social home page Coder Social logo

robertcraigie / pyright-python Goto Github PK

View Code? Open in Web Editor NEW
163.0 4.0 22.0 291 KB

Python command line wrapper for pyright, a static type checker

Home Page: https://pypi.org/project/pyright/

License: MIT License

Python 95.34% Dockerfile 4.66%
python pip typechecking cli

pyright-python's Introduction

Pyright for Python

Downloads PyPI Supported python versions

This project is not affiliated with Microsoft in any way, shape, or form

Pyright for Python is a Python command-line wrapper over pyright, a static type checker for Python.

Installation

Use the package manager pip to install pyright.

pip install pyright

Usage

Pyright can be invoked using two different methods

pyright --help

or

python3 -m pyright --help

Pyright for Python should work exactly the same as pyright does, see the pyright documentation for details on how to make use of pyright.

Pre-commit

You can also setup pyright to run automatically before each commit by setting up pre-commit and registering pyright in your .pre-commit-config.yaml file

repos:
  - repo: https://github.com/RobertCraigie/pyright-python
    rev: v1.1.379
    hooks:
    - id: pyright

Pre-commit will install pyright-python in its own virtual environment which can cause pyright to not be able to detect your installed dependencies.

To fix this you can either tell pre-commit to also install those dependencies or explicitly tell pyright which virtual environment to use by updating your pyright configuration file:

[tool.pyright]
# ...
venvPath = "."
venv = ".venv"

Motivation

Pyright is written in TypeScript, requiring node to be installed, and is normally installed with npm. This could be an entry barrier for some Python developers as they may not have node or npm installed on their machine; I wanted to make pyright as easy to install as any normal Python package.

How Pyright for Python Works

This project works by first checking if node is in the PATH. If it is not, then we download node at runtime using nodeenv, then install the pyright npm package using npm and finally, run the downloaded JS with node.

Automatically keeping pyright up to date

By default Pyright for Python is set to target a specific pyright version and new releases will be automatically created whenever a new pyright version is released. It is highly recommended to use an automatic dependency update tool such as dependabot.

If you would rather not have to update your installation every time a new pyright release is created then you can automatically use the latest available pyright version by setting the environment variable PYRIGHT_PYTHON_FORCE_VERSION to latest.

Configuration

You can configure Pyright for Python using environment variables.

Debugging

Set PYRIGHT_PYTHON_DEBUG to any value.

Modify Pyright Version

Set PYRIGHT_PYTHON_FORCE_VERSION to the desired version, e.g. 1.1.156, latest

Keeping Pyright and Pylance in sync

Set PYRIGHT_PYTHON_PYLANCE_VERSION to your Pylance version, e.g. 2023.11.11, latest-release, latest-prerelease. The corresponding Pyright version will be used. See Pylance's changelog for details on recent releases. Note that PYRIGHT_PYTHON_FORCE_VERSION takes precedence over PYRIGHT_PYTHON_PYLANCE_VERSION, so you'll want to set one or the other, not both.

Show NPM logs

By default, Pyright for Python disables npm error messages, if you want to display the npm error messages then set PYRIGHT_PYTHON_VERBOSE to any truthy value.

Modify NPM Package Location

Pyright for Python will resolve the root cache directory by checking the following environment variables, in order:

  • PYRIGHT_PYTHON_CACHE_DIR
  • XDG_CACHE_HOME

If neither of them are set it defaults to ~/.cache

Force Node Env

Set PYRIGHT_PYTHON_GLOBAL_NODE to any non-truthy value, i.e. anything apart from 1, t, on, or true. e.g. off You can optionally choose the version of node used by setting PYRIGHT_PYTHON_NODE_VERSION to the desired version

Modify Node Env Location

Set PYRIGHT_PYTHON_ENV_DIR to a valid nodeenv directory. e.g. ~/.cache/nodeenv

Ignore Warnings

Set PYRIGHT_PYTHON_IGNORE_WARNINGS to a truthy value, e.g. 1, t, on, or true.

Pyright for Python will print warnings for the following case(s)

  • There is a new Pyright version available.

Contributing

All pull requests are welcome.

License

MIT

pyright-python's People

Contributors

artificial-aidan avatar bersbersbers avatar debonte avatar demberto avatar francescelies avatar googolgenius avatar kianmeng avatar lukebakken avatar matthewlloyd avatar mjkramer avatar ndryden avatar q0w avatar rbizos avatar robertcraigie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

pyright-python's Issues

Add support for offline usage

Obviously due to the nature of this project we cannot add full support for offline usage but we should support it after a single run.

Comment from #43.

there is nothing directly in pyright-python that would mean offline usage could not be supported. It seems to be that npx is making requests itself even after the pyright NPM package has been installed once. Looks like we would have to move away from npx and directly install pyright using npm to a cached directory.

Clarify auto-upgrade behavior?

I am looking into using this project to run pyright as a pre-commit hook.

https://github.com/RobertCraigie/pyright-python/#readme currently says:

We also automatically upgrade the pyright npm package to its latest version on every run, see below for how to change this behaviour.

But the next sentence says:

By default Pyright for Python is set to target a specific pyright version...

These two sentences seem to contradict each other?

Is the default behavior the latter, i.e. to pin to a specific pyright version, so as to not defeat reproducible CI, and let users run pre-commit autoupdate as usual when they want to upgrade so they can do so in a controlled fashion? If so, then what is the first sentence trying to say?

Thanks for clarifying, and for maintaining this project.

pyright failing with SIGABRT

Fresh install of pyright with this wrapper fails with cryptic error.

System: MacOs 12.6.3, Python3.11

(venv) ~/P/py11 $ pip install pyright                                                                                              (base) 10:26:13
Collecting pyright
  Downloading https://repo/artifactory/api/pypi/python-virtual/packages/packages/8e/00/37250aaef114b0d383487571ac8e3a6ff8691c68f165d25ca57839e7c952/pyright-1.1.299-py3-none-any.whl (17 kB)
Collecting nodeenv>=1.6.0
  Downloading https://repo/artifactory/api/pypi/python-virtual/packages/packages/96/a8/d3b5baead78adadacb99e7281b3e842126da825cf53df61688cfc8b8ff91/nodeenv-1.7.0-py2.py3-none-any.whl (21 kB)
Requirement already satisfied: setuptools in ./venv/lib/python3.11/site-packages (from nodeenv>=1.6.0->pyright) (60.2.0)
Installing collected packages: nodeenv, pyright
Successfully installed nodeenv-1.7.0 pyright-1.1.299
WARNING: You are using pip version 21.3.1; however, version 23.0.1 is available.
You should consider upgrading via the '/Users/kai7rng/PycharmProjects/py11/venv/bin/python -m pip install --upgrade pip' command.
(venv) ~/P/py11 $ pyright --version                                                                                                (base) 10:26:31
dyld[50242]: Library not loaded: '/usr/local/opt/icu4c/lib/libicui18n.71.dylib'
  Referenced from: '/usr/local/Cellar/node/18.10.0/bin/node'
  Reason: tried: '/usr/local/opt/icu4c/lib/libicui18n.71.dylib' (no such file), '/usr/local/lib/libicui18n.71.dylib' (no such file), '/usr/lib/libicui18n.71.dylib' (no such file), '/usr/local/Cellar/icu4c/72.1/lib/libicui18n.71.dylib' (no such file), '/usr/local/lib/libicui18n.71.dylib' (no such file), '/usr/lib/libicui18n.71.dylib' (no such file)
Traceback (most recent call last):
  File "/Users/kai7rng/PycharmProjects/py11/venv/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
             ^^^^^^^^^^^^
  File "/Users/kai7rng/PycharmProjects/py11/venv/lib/python3.11/site-packages/pyright/cli.py", line 34, in entrypoint
    sys.exit(main(sys.argv[1:]))
             ^^^^^^^^^^^^^^^^^^
  File "/Users/kai7rng/PycharmProjects/py11/venv/lib/python3.11/site-packages/pyright/cli.py", line 19, in main
    return run(*args, **kwargs).returncode
           ^^^^^^^^^^^^^^^^^^^^
  File "/Users/kai7rng/PycharmProjects/py11/venv/lib/python3.11/site-packages/pyright/cli.py", line 25, in run
    pkg_dir = install_pyright(args, quiet=None)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/kai7rng/PycharmProjects/py11/venv/lib/python3.11/site-packages/pyright/_utils.py", line 61, in install_pyright
    node.run(
  File "/Users/kai7rng/PycharmProjects/py11/venv/lib/python3.11/site-packages/pyright/node.py", line 115, in run
    return subprocess.run(node_args, env=env, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 569, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/usr/local/bin/npm', 'install', '[email protected]']' died with <Signals.SIGABRT: 6>.

pre-commit: Temporary failure in name resolution

I am unable to use this action with pre-commit.ci, see this run: https://results.pre-commit.ci/run/github/590722908/1679661177.MbHCS6NnRWWUN9bswKc3Eg

/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py:26: DeprecationWarning: 'pipes' is deprecated and slated for removal in Python 3.13
  import pipes
Traceback (most recent call last):
  File "/usr/lib/python3.11/urllib/request.py", line 1348, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "/usr/lib/python3.11/http/client.py", line 1282, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.11/http/client.py", line 1328, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.11/http/client.py", line 1277, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.11/http/client.py", line 1037, in _send_output
    self.send(msg)
  File "/usr/lib/python3.11/http/client.py", line 975, in send
    self.connect()
  File "/usr/lib/python3.11/http/client.py", line 1447, in connect
    super().connect()
  File "/usr/lib/python3.11/http/client.py", line 941, in connect
    self.sock = self._create_connection(
                ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/socket.py", line 827, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/socket.py", line 962, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
socket.gaierror: [Errno -3] Temporary failure in name resolution

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py", line 1519, in <module>
    main()
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py", line 1093, in main
    args.node = get_last_stable_node_version()
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py", line 1026, in get_last_stable_node_version
    return _get_versions_json()[0]['version'].lstrip('v')
           ^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py", line 1002, in _get_versions_json
    response = urlopen('%s/index.json' % src_base_url)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/nodeenv.py", line 624, in urlopen
    return urllib2.urlopen(req)
           ^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 519, in open
    response = self._open(req, data)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 536, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 496, in _call_chain
    result = func(*args)
             ^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 1391, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/urllib/request.py", line 1351, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
Traceback (most recent call last):
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
             ^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/cli.py", line 34, in entrypoint
    sys.exit(main(sys.argv[1:]))
             ^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/cli.py", line 19, in main
    return run(*args, **kwargs).returncode
           ^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/cli.py", line 25, in run
    pkg_dir = install_pyright(args, quiet=None)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/_utils.py", line 61, in install_pyright
    node.run(
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/node.py", line 98, in run
    binary = _ensure_available(target)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/node.py", line 37, in _ensure_available
    return Binary(path=_ensure_node_env(target), strategy=Strategy.NODEENV)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/node.py", line 64, in _ensure_node_env
    _install_node_env()
  File "/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/lib/python3.11/site-packages/pyright/node.py", line 91, in _install_node_env
    subprocess.run(args, check=True)
  File "/usr/lib/python3.11/subprocess.py", line 571, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/pc/clone/uy_ziTtWRGGmDsK6CW-fSA/py_env-python3/bin/python', '-m', 'nodeenv', '/tmp/cache/pyright-python/nodeenv']' returned non-zero exit status 1.

getting error: Operator "+" not supported for "None" (reportOptionalOperand)

So I have this code that pyright produces error: Operator "+" not supported for "None" (reportOptionalOperand)

#!/usr/bin/env python3
import os

#testing when contatenate simpole strings
a_string = ""
b_string = "test"
a_string = a_string+"/"+b_string
print(type(a_string))
print(b_string)


#testing with contatenate with os.getenv
home = os.getenv("HOME")
print(type(home))
update_home = home + "/rock"
print(home)
print(update_home)

The code runs fine but pyright gives the error.

$ pyright test.py 
No configuration file found.
No pyproject.toml file found.
stubPath /home/alek/projects/testing/python/String/typings is not a valid directory.
Assuming Python platform Linux
Searching for source files
Found 1 source file
pyright 1.1.277
/home/alek/projects/testing/python/String/test.py
  /home/alek/projects/testing/python/String/test.py:15:15 - error: Operator "+" not supported for "None" (reportOptionalOperand)
1 error, 0 warnings, 0 informations 
Completed in 0.577sec

If I put a str(home) like so update_home = str(home) + "/rock" I don't get an error
it just doesn't make sense to me since both instances are str classes

Feature request: symlink to latest version in cache

pyright-python maintains a cache of versions, eg:

โฏ ls ~/.cache/pyright-python/
1.1.296 1.1.298

It would be nice to have a stable latest symlink to to the latest version, eg:

โฏ ls -al ~/.cache/pyright-python/
total 0
drwxr-xr-x   5 tekumara  staff  160 13 Mar 09:49 .
drwxr-xr-x  15 tekumara  staff  480 13 Mar 09:48 ..
drwxr-xr-x   5 tekumara  staff  160  6 Mar 12:13 1.1.296
drwxr-xr-x   5 tekumara  staff  160 13 Mar 09:48 1.1.298
lrwxr-xr-x   1 tekumara  staff    7 13 Mar 09:49 latest -> 1.1.298

A stable symlink could be used globally, from any bash script/Makefile commands, or for interactive usage.

(It also avoids going through the python interpreter and so has a lower startup time).

npx version error

Hello, I use python 3.8, pyright 1.1.239
config.toml

[tool.pyright]
pythonVersion = "3.8"
pythonPlatform = "Linux"
reportPrivateImportUsage = false
python.analysis.useLibraryCodeForTypes = true

docker-compose where start pyright but i got error:

File "/usr/local/lib/python3.8/site-packages/pyright/node.py", line 121, in version
    raise errors.VersionCheckFailed(
pyright.errors.VersionCheckFailed: Could not find version from `npx --version`, see output above
npm notice 
npm notice New minor version of npm available! 8.6.0 -> 8.7.0
npm notice Changelog: <https://github.com/npm/cli/releases/tag/v8.7.0>
npm notice Run `npm install -g [email protected]` to update!
npm notice  

Can't fix it

Unable to run pyright pre-commit under VPN

Thanks a lot for the nice integration.

I am facing a strange issue when integrating pyright pre-commit with my repository. Everything works fine when I am not using a company VPN. However, as soon as I activate it, the check gets hung with a blinking cursor:

$ pre-commit run --all-files
black....................................................................Passed
flake8...................................................................Passed
trim trailing whitespace.................................................Passed
fix end of files.........................................................Passed
isort (python)...........................................................Passed
pyupgrade................................................................Passed
pyright..................................................................

(v1.1.289) langserver.index.js does not exist

I get that error by just calling the following.

โฏ pyright-langserver.exe --help

up to date, audited 2 packages in 778ms

found 0 vulnerabilities
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\s\myrepo\venv\py311\Scripts\pyright-langserver.exe\__main__.py", line 7, in <module>
  File "C:\Users\FrancescElies\src\pyright-python\pyright\langserver.py", line 57, in entrypoint
    sys.exit(main(*sys.argv[1:]))
             ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FrancescElies\src\pyright-python\pyright\langserver.py", line 26, in main
    return run(*args, **kwargs).returncode
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\FrancescElies\src\pyright-python\pyright\langserver.py", line 51, in run
    raise RuntimeError(f'Expected language server entrypoint: {binary} to exist')
RuntimeError: Expected language server entrypoint: C:\Users\FRANCE~1\AppData\Local\Temp\pyright-python-langserver.FrancescElies\node_modules\pyright\langserver.index.js to exist

I see node output which tried to install node on the temp path above but that folder is empty.
This corresponds to the execution of this line of code

up to date, audited 2 packages in 778ms

found 0 vulnerabilities

Despite of npm install the binary does not exist

What am I doing wrong?

โฏ npm --version
8.14.0

pyright-langserver does not start if username contains an `@` symbol

On my work laptop (macOS), my username is my email address. When I install the pyright PyPI package and try to run pyright-langserver, I get the following error (I replace the original email address with [email protected]):

npm ERR! Invalid name: "[email protected]"

The issue seems to be that langserver.py includes the return value of getpass.getuser()) in the name of a temporarily generated NPM package. As @ is not a valid character for an NPM package name, the above error occurs.

To reproduce: Set LOGNAME to a username with an @ character.

# This fails:
[email protected] pyright-langserver --stdio
 
# This works as expected:
LOGNAME=alice pyright-langserver --stdio

Possible fix: Remove or replace special characters in usernames before constructing the temporary NPM package name, or do not rely on the username at all, e.g. by using a random suffix.

LSP Error lanunching pyright-langserver

Launching the server entrypoint (pyright-langserver) as an editor would launch it (Neovim with native LSP support in my case), when trying to get LSP live information results in the following error:

$ pyright-langserver --stdio

up to date, audited 203 packages in 2s

found 0 vulnerabilities
Traceback (most recent call last):
  File "/tmp/.venv/bin/pyright-langserver", line 8, in <module>
    sys.exit(entrypoint())
  File "/tmp/.venv/lib/python3.10/site-packages/pyright/langserver.py", line 57, in entrypoint
    sys.exit(main(*sys.argv[1:]))
  File "/tmp/.venv/lib/python3.10/site-packages/pyright/langserver.py", line 26, in main
    return run(*args, **kwargs).returncode
  File "/tmp/.venv/lib/python3.10/site-packages/pyright/langserver.py", line 51, in run
    raise RuntimeError(f'Expected language server entrypoint: {binary} to exist')
RuntimeError: Expected language server entrypoint: /tmp/pyright-python-langserver.baco/node_modules/pyright/langserver.index.js to exist

poetry run pyright: Installs static node, but does not put it on the path before exec

Reproduction repo is here: https://github.com/blast-hardcheese/pyright-python-bug

Description

Despite installing a dedicated version of node, the system node is attempted to be used.

Full traceback is here:

/app # PYRIGHT_PYTHON_FORCE_VERSION=latest poetry run pyright
/app/.venv/lib/python3.11/site-packages/nodeenv.py:26: DeprecationWarning: 'pipes' is deprecated and slated for removal in Python 3.13
  import pipes
 * Install prebuilt node (19.7.0) ..... done.
env: can't execute 'node': No such file or directory

Traceback (most recent call last):
  File "/app/.venv/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
             ^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/pyright/cli.py", line 81, in entrypoint
    sys.exit(main(sys.argv[1:]))
             ^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/pyright/cli.py", line 21, in main
    return run(*args, **kwargs).returncode
           ^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/pyright/cli.py", line 29, in run
    version = node.latest('pyright')
              ^^^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/pyright/node.py", line 147, in latest
    raise errors.VersionCheckFailed(
pyright.errors.VersionCheckFailed: Version check for pyright failed, see output above.

Infinite recursive processes started with version 1.1.242

After upgrading pyright to 1.1.242, I'm seeing the following behavior. This persists after doing a clean install, and isn't seen with version 1.1.241:

$ PYRIGHT_PYTHON_DEBUG=1 pyright --help
2022-04-30 22:58:51,642 - DEBUG - pyright.utils - Latest pyright-python version is: 1.1.242
2022-04-30 22:58:51,642 - DEBUG - pyright.node - Checking for global target binary: npx
2022-04-30 22:58:51,642 - DEBUG - pyright.node - Global target binary: npx not found
2022-04-30 22:58:51,643 - DEBUG - pyright.node - Checking for nodeenv npx binary
2022-04-30 22:58:51,643 - DEBUG - pyright.node - Environment not found at /tmp/pyright-python.jcristharif/env
2022-04-30 22:58:51,643 - DEBUG - pyright.node - Installing nodeenv to /tmp/pyright-python.jcristharif/env
2022-04-30 22:58:51,643 - DEBUG - pyright.node - Running command with args: ['/home/jcristharif/miniconda3/envs/python-temp/bin/python3.9', '-m', 'nodeenv', '/tmp/pyright-python.jcristharif/env']
 * Install prebuilt node (18.0.0) ..... done.
2022-04-30 22:58:56,092 - DEBUG - pyright.node - Running node command with args: ['bash', '-c', '. /tmp/pyright-python.jcristharif/env/bin/activate && npx --version']
2022-04-30 22:58:56,298 - DEBUG - pyright.node - Version check for npx returning (8, 6, 0)
2022-04-30 22:57:26,438 - DEBUG - pyright.node - Checking for global target binary: npx
2022-04-30 22:57:26,439 - DEBUG - pyright.node - Global target binary: npx not found
2022-04-30 22:57:26,439 - DEBUG - pyright.node - Checking for nodeenv npx binary
2022-04-30 22:57:26,439 - DEBUG - pyright.node - Environment exists at /tmp/pyright-python.jcristharif/env
2022-04-30 22:57:26,440 - DEBUG - pyright.node - Running node command with args: ['bash', '-c', '. /tmp/pyright-python.jcristharif/env/bin/activate && npx --version']
2022-04-30 22:57:26,677 - DEBUG - pyright.node - Version check for npx returning (8, 6, 0)
2022-04-30 22:57:26,677 - DEBUG - pyright.node - Checking for global target binary: npx
2022-04-30 22:57:26,677 - DEBUG - pyright.node - Global target binary: npx not found
2022-04-30 22:57:26,678 - DEBUG - pyright.node - Checking for nodeenv npx binary
2022-04-30 22:57:26,678 - DEBUG - pyright.node - Environment exists at /tmp/pyright-python.jcristharif/env
2022-04-30 22:57:26,678 - DEBUG - pyright.node - Running node command with args: ['bash', '-c', '. /tmp/pyright-python.jcristharif/env/bin/activate && npx --silent --yes -- [email protected] --help']
2022-04-30 22:57:27,582 - DEBUG - pyright.utils - Latest pyright-python version is: 1.1.242
# this just repeats for forever.

As best as I can tell the subprocess command ['bash', '-c', '. /tmp/pyright-python.jcristharif/env/bin/activate && npx --silent --yes -- [email protected] --help'] is kicking off the Python CLI again, recursing for forever. After a few seconds a killall pyright terminates 10s of processes.

I'm running Linux, with no nodejs on PATH. Version 1.1.241 works fine, it's only on 1.1.242 that I see the above behavior.

pyright-langserver wrapper produces extraneous output

Running the pyright-langserver wrapper produces extraneous, non-JSONRPC output to stdout:

$ pyright-langserver --stdio 2> /dev/null                                                     
Wrote to /tmp/ndryden/pyright-python-langserver.1602085020987684455/package.json:

{
  "name": "pyright-python-langserver.1602085020987684455",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}



added 1 package, and audited 2 packages in 2s

found 0 vulnerabilities
Content-Length: 119

{"jsonrpc":"2.0","method":"window/logMessage","params":{"type":3,"message":"Pyright language server 1.1.293 starting"}}Content-Length: 187

{"jsonrpc":"2.0","method":"window/logMessage","params":{"type":3,"message":"Server root directory: /tmp/ndryden/pyright-python-langserver.1602085020987684455/node_modules/pyright/dist/"}}

This appears to have been introduced in release v1.1.291, as v1.1.290 does not exhibit this. In particular, this breaks eglot, the LSP interface in emacs (see discussion here).

It looks like this output comes from the added npm init call in 04f1508.

A simple fix would be to suppress the output of that by adding stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL to the node.run call. If this seems reasonable, I can PR it.

Pyright won't work again after getting interrupted through Ctrl+C

It turns out that force stopping pyright with Ctrl+C during the time a loading bar is visible on the screen (presumably npx running something), some crucial cleanup work is skipped, and a folder named .pyright-random_string stays present in the node modules directory (as an example of full path for my case: /home/itsdrike/.local/share/npm/_npx/77993788984d59ab/node_modules/.pyright-WRkpBM9m) when it should have gotten removed.

Because this folder didn't get deleted, running pyright the next time leads to problems from npx, detecting that the directory it wants to make is already there, and ending with 217 error code, which doesn't give the user any description on what happened (because of the --silent flag). This is the actual error output from npx when using it manually to see the messages it produces (without silent):
image

Full traceback of the keyboard interrupt error propagation which did lead to this folder not getting removed:

Traceback (most recent call last):
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/site-packages/pyright/cli.py", line 81, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/site-packages/pyright/cli.py", line 21, in main
    return run(*args, **kwargs).returncode
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/site-packages/pyright/cli.py", line 57, in run
    return node.run('npx', *pre_args, f'pyright@{version}', *args, **kwargs)
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/site-packages/pyright/node.py", line 112, in run
    return subprocess.run(node_args, env=env, **kwargs)
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/subprocess.py", line 503, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/subprocess.py", line 1141, in communicate
    self.wait()
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/subprocess.py", line 1204, in wait
    return self._wait(timeout=timeout)
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/subprocess.py", line 1938, in _wait
    (pid, sts) = self._try_wait(0)
  File "/home/itsdrike/.local/share/pyenv/versions/3.10.3/lib/python3.10/subprocess.py", line 1896, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt

I actually already encountered this issue a good while ago, but I had no idea what was causing it and it ended up getting resolved by deleting the folder made by npx holding pyright. I mentioned this in #37, and since that, I did encounter the issue a few times again, but I blamed it on npx running poorly with Arch Linux, or something like that. However after a lot of debugging, I finally figured out why this was happening.

When running pyright with npx alone outside of using this library (running through python's subprocesses), npx is able to handle Ctrl+C occurring and gracefully exits after a while (taking it's time to remove this temporary folder, and perhaps do some other cleanup too). This can be seen from this error message:
image

However running pyright through the script this library provides only produces the python's traceback error, and leads to the main python process being stopped, which then most likely kills the npx subprocess forcefully, and prevents it's cleanup from running.

This should be handled by catching the KeyboardInterrupt while waiting on the npx process, and if it was catched, ending the process gracefully and waiting for it to close before actually exitting the python script (perhaps by re-raising the exception, or with a simple message and sys.exit call with non-zero code).

Since npx can take a while (few seconds) for it's cleanup to occur, and the script is running it with the --silent flag, it would probably be a good idea to also print out some message about this closing processes getting started immediately after the user pressed ctrl+c, to avoid them pressing it again, and causing another keyboard interrupt error during the graceful closing process, leading to this issue once again. Maybe even another handle which would that time indeed forcefully terminate the process, but also let the user know about this issue.

npx permission issue when PWD has different owner compared to install

a bit of context:

  • running things in docker in this case
  • docker image has a bunch of pre-commit hooks preinstalled
  • then mounting $PWD to actually run lint checks in CI
  • however github actions PWD does not belong to root which causes issues for npx
  • docker runtime user is root
  • since pwd in container has a different owner npx is not happy:
root@5ed5df3566d5:/home/yay# source /tmp/pyright-python.root/env/bin/activate

(env) root@5ed5df3566d5:/home/yay# id
uid=0(root) gid=0(root) groups=0(root)

(env) root@5ed5df3566d5:/home/yay# ls -la . | head -n2
total 28
drwx------ 1  970  970  218 Aug  2 03:07 .

(env) root@5ed5df3566d5:/home/yay# which npx
/tmp/pyright-python.root/env/bin/npx

(env) root@5ed5df3566d5:/home/yay# npx --version
8.19.1

(env) root@5ed5df3566d5:/home/yay# npx -- [email protected] --version
sh: 1: pyright: Permission denied

however if I cd to root home folder it works fine:

(env) root@5ed5df3566d5:/home/yay# cd

(env) root@5ed5df3566d5:~# npx -- [email protected] --version
pyright 1.1.271

any reason npx is used in general? it seems to be deprecated https://github.com/npm/npx

Support custom nodeenv options

This is transferred from microsoft/pyright#3414. Possibly related to #56.

pyright crashes with the following error after node 18 has been released.

> pyright myproject
 * Install prebuilt node (18.0.0) ..... done.
node: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by node)

I'm running ubuntu 18.04. There seems to be no obvious (/convenient) way to upgrade my glibc 2.27 to 2.28. After a little digging, I found that pyright is using nodeenv to create a clean node environment under /tmp/pyright.username, and nodeenv automatically looks for latest stable. Unfortunately, although nodeenv provides way to restrain the node version, pyright didn't expose such ability.

A possible solution is to constrain the node versions in pyright. I did that by hacking pyright's python package.

def _install_node_env() -> None:
    log.debug('Installing nodeenv to %s', ENV_DIR)
    args = [sys.executable, '-m', 'nodeenv', str(ENV_DIR), '--node=16.15.0']  # I added node version here
    log.debug('Running command with args: %s', args)
    subprocess.run(args, check=True)

I was hoping that pyright could address that natively.

Consider pinning the internal pyright version and auto-releasing new pyright-python versions

Problem

Our current solution does not work well with CI.

CI runs should be reproducible, however when using our wrapper, a CI run could seemingly randomly fail due to bug fixes / changes in pyright's type checking in a new release. This makes people set PYRIGHT_PYTHON_FORCE_VERSION and then never update it, causing the issue that Eric originally wanted to avoid.

Solution

We should create a GitHub action workflow that will run regularly, checking if there is a new pyright version available. When a new version is detected, the workflow should then:

  • update the internal pyright version to it's latest
  • bump our version
  • create a PR
  • merge once checks pass
  • publish a new release to PyPi

Users that have a solution like Dependabot enabled will then receive a notification that there is a new pyright version available. #22 would also help people keep their pyright version up to date.

However, some users might not want to have to manually update their pyright-python version every time a new pyright version is released, we should also provide an escape hatch to keep the old behaviour.

Additional context

https://github.com/hikari-py/hikari/blob/965d6e8a4c7685a7b6d9fd1b53cec3609f0821e3/pipelines/config.py#L40

non-zero exit status 2 when running pyright

I'm trying to learn how to use pyright on the panel package to improve the way it works in VS Code. But I cannot run it. And the error message is not very helpful.

If I

$pip install pyright
$pyright --verifytypes panel

I get a non-zero exit status 2.

$ pip install pyright
Looking in indexes: https://pypi.org/simple, https://masma:****@pkgs.dev.azure.com/dongenergy-p/_packaging/MarketTrading%40Local/pypi/simple/, https://masma:****@pkgs.dev.azure.com/dongenergy-p/_packaging/analytics-workspace/pypi/simple/
Collecting pyright
  Downloading pyright-1.1.238-py3-none-any.whl (15 kB)
Collecting nodeenv>=1.6.0
  Using cached nodeenv-1.6.0-py2.py3-none-any.whl (21 kB)
Installing collected packages: nodeenv, pyright
Successfully installed nodeenv-1.6.0 pyright-1.1.238
WARNING: You are using pip version 20.2.3; however, version 22.0.4 is available.
You should consider upgrading via the 'c:\repos\private\now\.venv\scripts\python.exe -m pip install --upgrade pip' command.     
(.venv) 
MASMA@PC81978 MINGW64 /c/repos/private/now
$ pyright --verifytypes panel
 * Environment already exists: C:\Users\masma\AppData\Local\Temp\pyright-python.MASMA\env
Traceback (most recent call last):
  File "C:\Program Files\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\repos\private\now\.venv\Scripts\pyright.exe\__main__.py", line 7, in <module>
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\cli.py", line 72, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\cli.py", line 20, in main
    return run(*args, **kwargs).returncode
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\cli.py", line 36, in run
    npx = node.version('npx')
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\node.py", line 116, in version
    proc = run(target, '--version', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\node.py", line 86, in run
    binary = _ensure_available(target)
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\node.py", line 34, in _ensure_available
    return Binary(path=_ensure_node_env(target), strategy=Strategy.NODEENV)
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\node.py", line 52, in _ensure_node_env
    _install_node_env()
  File "c:\repos\private\now\.venv\lib\site-packages\pyright\node.py", line 79, in _install_node_env
    subprocess.run(args, check=True)
  File "C:\Program Files\Python39\lib\subprocess.py", line 528, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['c:\\repos\\private\\now\\.venv\\scripts\\python.exe', '-m', 'nodeenv', 'C:\\Users\\masma\\AppData\\Local\\Temp\\pyright-python.MASMA\\env']' returned non-zero exit status 2.

My first suggestion would be to provide a better error message: Please tell me the cause and how to fix it.
Secondly it might also be an idea to improve the installation instructions to tell that it is not enough to pip install pyright - you will need to also install node???? Its probably because I don't have node installed ??

Additional Context

OS: Win 10 Enterprise
Terminal: Git Bash

Pyright raising errors.VersionCheckFailed even though it exists

Similar to the issue below.
Originally posted by @RobertCraigie in #56 (comment)

see logs

root@691b3d39624c:/app# env PYRIGHT_PYTHON_IGNORE_NPX_CHECK=1 pyright -p pyrightconfig-ci.json 
2022-06-13 12:06:58,393 - DEBUG - pyright.node - Checking for global target binary: npm
2022-06-13 12:06:58,404 - DEBUG - pyright.node - Found global binary at: /usr/bin/npm
2022-06-13 12:06:58,405 - DEBUG - pyright.node - Global binary exists at: /usr/bin/npm
2022-06-13 12:06:58,407 - DEBUG - pyright.node - Running node command with args: ['/usr/bin/npm', 'info', 'pyright', 'version']
2022-06-13 12:07:04,976 - DEBUG - pyright.node - Version check for pyright returning 1.1.254
2022-06-13 12:07:04,980 - DEBUG - pyright.node - Checking for global target binary: npx
2022-06-13 12:07:04,986 - DEBUG - pyright.node - Found global binary at: /usr/bin/npx
2022-06-13 12:07:04,988 - DEBUG - pyright.node - Global binary exists at: /usr/bin/npx
2022-06-13 12:07:04,992 - DEBUG - pyright.node - Running node command with args: ['/usr/bin/npx', '--version']
2022-06-13 12:07:07,736 - DEBUG - pyright.node - Version check for npx returning (8, 11, 0)
2022-06-13 12:07:07,738 - DEBUG - pyright.node - Checking for global target binary: npx
2022-06-13 12:07:07,739 - DEBUG - pyright.node - Found global binary at: /usr/bin/npx
2022-06-13 12:07:07,739 - DEBUG - pyright.node - Global binary exists at: /usr/bin/npx
2022-06-13 12:07:07,740 - DEBUG - pyright.node - Running node command with args: ['/usr/bin/npx', '--silent', '--yes', '--', '[email protected]', '-p', 'pyrightconfig-ci.json']
2022-06-13 12:07:14,440 - DEBUG - pyright.node - Checking for global target binary: npm
2022-06-13 12:07:14,445 - DEBUG - pyright.node - Found global binary at: /usr/bin/npm
2022-06-13 12:07:14,446 - DEBUG - pyright.node - Global binary exists at: /usr/bin/npm
2022-06-13 12:07:14,449 - DEBUG - pyright.node - Running node command with args: ['/usr/bin/npm', 'info', 'pyright', 'version']

Traceback (most recent call last):
  File "/usr/local/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
  File "/usr/local/lib/python3.10/site-packages/pyright/cli.py", line 81, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "/usr/local/lib/python3.10/site-packages/pyright/cli.py", line 21, in main
    return run(*args, **kwargs).returncode
  File "/usr/local/lib/python3.10/site-packages/pyright/cli.py", line 29, in run
    version = node.latest('pyright')
  File "/usr/local/lib/python3.10/site-packages/pyright/node.py", line 145, in latest
    raise errors.VersionCheckFailed(
pyright.errors.VersionCheckFailed: Version check for pyright failed, see output above.
root@691b3d39624c:/app# 
root@691b3d39624c:/app# /usr/bin/npm info pyright version
1.1.254
root@691b3d39624c:/app# 

pyright returning error code 243 with fnm and poetry

When running poetry run pyright, pyright exits with error code 243 with no additional output. This issue is possibly related to fnm or poetry.

nick:~/dev/_projects/python master* PYRIGHT_PYTHON_DEBUG=1 poetry run pyright
2023-02-17 16:14:34,492 - DEBUG - pyright.node - Checking for global target binary: npm
2023-02-17 16:14:34,492 - DEBUG - pyright.node - Found global binary at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npm
2023-02-17 16:14:34,493 - DEBUG - pyright.node - Global binary exists at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npm
2023-02-17 16:14:34,493 - DEBUG - pyright.node - Running node command with args: ['/var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npm', 'info', 'pyright', 'version']
2023-02-17 16:14:35,007 - DEBUG - pyright.node - Version check for pyright returning 1.1.294
2023-02-17 16:14:35,007 - DEBUG - pyright.node - Checking for global target binary: npx
2023-02-17 16:14:35,008 - DEBUG - pyright.node - Found global binary at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx
2023-02-17 16:14:35,008 - DEBUG - pyright.node - Global binary exists at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx
2023-02-17 16:14:35,008 - DEBUG - pyright.node - Running node command with args: ['/var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx', '--version']
2023-02-17 16:14:35,367 - DEBUG - pyright.node - Version check for npx returning (8, 5, 0)
2023-02-17 16:14:35,367 - DEBUG - pyright.node - Checking for global target binary: npx
2023-02-17 16:14:35,368 - DEBUG - pyright.node - Found global binary at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx
2023-02-17 16:14:35,368 - DEBUG - pyright.node - Global binary exists at: /var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx
2023-02-17 16:14:35,368 - DEBUG - pyright.node - Running node command with args: ['/var/folders/jv/262_sfyn0y354v1c1vx_9qq40000gn/T/fnm-shell-1820228/bin/npx', '--silent', '--yes', '[email protected]']
nick:~/dev/_projects/python master* echo $?
243
nick:~/dev/_projects/python master* PYRIGHT_PYTHON_VERBOSE=1 poetry run pyright
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /Users/nick/.npm/_npx/07f2536c0965b4ca
npm ERR! errno -13
npm ERR!
npm ERR! Your cache folder contains root-owned files, due to a bug in
npm ERR! previous versions of npm which has since been addressed.
npm ERR!
npm ERR! To permanently fix this problem, please run:
npm ERR!   sudo chown -R 501:20 "/Users/nick/.npm"

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/nick/.npm/_logs/2023-02-17T21_18_34_493Z-debug-0.log

Note that this issue can be worked around by directly invoking the node version pyright with the following command:

poetry run npx pyright

fnm --version 1.17.0
poetry --version Poetry (version 1.2.0)

pip-installed pyright hangs

Hello,

I've been previously using npm-installed pyright, and it worked. I was excited to try pip installed version, however it didn't work, not producing any useful input on --version or call w/o arguments.

Describe the bug

Pip installed version of pyright doesn't launch, asked to print version it only set ERRNO to 1 in 1 minute+ running time and made no output.

To Reproduce

in MacOs 11.6.3, Python 3.8.8,
pip install pyright==1.1.231
pyright --version -> no version outputted, ERRNO set.

(also tried on Python 3.9.6)

Expected behavior
Expected pip version of pyright to behave same as npm version.

Code

~ $ pip install pyright                                          (base) 08:08:37
...
Installing collected packages: nodeenv, pyright
Successfully installed nodeenv-1.6.0 pyright-1.1.231
~ $ pyright --version                                            (base) 08:08:45
~ [1] $ pyright --version                                        (base) 08:10:01
^CTraceback (most recent call last):
  File "~/opt/anaconda3/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
  File "~/opt/anaconda3/lib/python3.8/site-packages/pyright/cli.py", line 72, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "~/opt/anaconda3/lib/python3.8/site-packages/pyright/cli.py", line 20, in main
    return run(*args, **kwargs).returncode
  File "~/opt/anaconda3/lib/python3.8/site-packages/pyright/cli.py", line 48, in run
    return node.run('npx', *pre_args, f'pyright@{version}', *args, **kwargs)
  File "~/opt/anaconda3/lib/python3.8/site-packages/pyright/node.py", line 112, in run
    return subprocess.run(node_args, env=env, **kwargs)
  File "~/opt/anaconda3/lib/python3.8/subprocess.py", line 495, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "~/opt/anaconda3/lib/python3.8/subprocess.py", line 1020, in communicate
    self.wait()
  File "~/opt/anaconda3/lib/python3.8/subprocess.py", line 1083, in wait
    return self._wait(timeout=timeout)
  File "~/opt/anaconda3/lib/python3.8/subprocess.py", line 1808, in _wait
    (pid, sts) = self._try_wait(0)
  File "~/opt/anaconda3/lib/python3.8/subprocess.py", line 1766, in _try_wait
    (pid, sts) = os.waitpid(self.pid, wait_flags)
KeyboardInterrupt

Conflicting documentation on which pyright version is used by default

We also automatically upgrade the pyright npm package to its latest version on every run, see below for how to change this behaviour.

and

By default Pyright for Python is set to target a specific pyright version and new releases will be automatically created whenever a new pyright version is released. [...] If you would rather not have to update your installation every time a new pyright release is created then you can automatically use the latest available pyright version by setting the environment variable PYRIGHT_PYTHON_FORCE_VERSION to latest.

So which one is it? Automatically updated or do I need to configure to use latest?

Any potential issues running this with `asdf`?

๐Ÿ‘‹ @RobertCraigie โ€“ we're using Typescript and Python in our company and managing all the language runtimes with asdf.

Are you aware of asdf? If yes, can you foresee any potential issues if we were to start using pyright-python alongside asdf-managed Node.js? I'm just being extra cautious now because I desperately want to avoid messing our developers' Node environment.

PS: Our .tool-versions file looks like this right now:

# Node.js
nodejs 16.17.1
pnpm 7.17.1

# Python
poetry 1.3.2
python 3.11.1

"return non-zero exit status 2" failure coming from nodeenv. Windows temp-file dependent issue

On some Windows 10 machines, I'm running in to this failure when trying to start up pyright:

>c:\python36\python -m pyright
 * Environment already exists: C:\Users\admin\AppData\Local\Temp\pyright-python.admin\env
Traceback (most recent call last):
  File "c:\python36\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\python36\lib\site-packages\pyright\__main__.py", line 5, in <module>
    entrypoint()
  File "c:\python36\lib\site-packages\pyright\cli.py", line 46, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "c:\python36\lib\site-packages\pyright\cli.py", line 20, in main
    return run(*args, **kwargs).returncode
  File "c:\python36\lib\site-packages\pyright\cli.py", line 30, in run
    npx = node.version('npx')
  File "c:\python36\lib\site-packages\pyright\node.py", line 116, in version
    proc = run(target, '--version', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  File "c:\python36\lib\site-packages\pyright\node.py", line 86, in run
    binary = _ensure_available(target)
  File "c:\python36\lib\site-packages\pyright\node.py", line 34, in _ensure_available
    return Binary(path=_ensure_node_env(target), strategy=Strategy.NODEENV)
  File "c:\python36\lib\site-packages\pyright\node.py", line 52, in _ensure_node_env
    _install_node_env()
  File "c:\python36\lib\site-packages\pyright\node.py", line 79, in _install_node_env
    subprocess.run(args, check=True)
  File "c:\python36\lib\subprocess.py", line 418, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['c:\\python36\\python.exe', '-m', 'nodeenv', 'C:\\Users\\admin\\AppData\\Local\\Temp\\pyright-python.admin\\env']' returned non-zero exit status 2.

If I delete the temp folder that's listed, then running python -m pyright will pause while installing node but then immediately fail in a way that's similar to the above (during a _ensure_available call after the installation). Whereas whenever running python -m pyright after that it will fail immediately.

If running python -m nodeenv directly, I get the same message "Environment already exists" with a process return code 2.

So, return code 2 doesn't seem like an error to me -- that's good if the environment already exists, right?

Is the bug then that python-pyright is interpreting this error code 2 as a fatal error whereas it should be interpreting it as a success?

On a different Windows 10 machine, python-pyright appears to be working but the behaviour is quite different. Each time I run, it reinstalls node in a new temp folder. The temp file paths are things like C:\Users\admin\AppData\Local\Temp\pyright-18412-XGp1w1LhcUJv, and I have a build up of quite a number of those temp folders with different random alpanumeric endings. (they seem empty, so at least it's not a major memory leak of leaving a full node installation in each of those).

Should python-pyright be reinstalling node each time it is run, or trying to reuse existing temp instlallations? If it should be trying to reuse, then the behaviour on the "working" machine also seems like a bug.

I'm not sure what is different about my different Windows machines where they seem to use a different temp-folder strategy like this.

Warning caused by wrong argument passed to pyright by the wrapper script

Running the pyright bin installed from this module causes the following call to npx:

npx --silent --yes [email protected]

If an argument is present (e.g. pyright foo) this changes to:

npx --silent --yes [email protected] -- foo

This causes the following warning from pyright:

File or directory "/Users/tim/repos/github.com/smb-ag/reels/--" does not exist.

This is because the -- is passed from npx to pyright where it is not handled in the typical gnunix way and instead understood as the first "file" argument to pyright.
As per npx docs the correct call should be:
(using npm exec -- <pkg>[@<version>] [args...] syntax)

npx --silent --yes -- [email protected] foo

cli for the wrapper itself

First, thank you for the tool, it makes using pyright very simple.

A cli to manage the settings of the wrapper itself, and some form of configuration file for the wrapper would be neat to see.

This would probably be able to indirectly resolve #8 as well, by having a global config and/or local config.

pyright failing with traceback to nodeenv

Note: if you are reporting a wrong signature of a function or a class in the standard library, then the typeshed tracker is better suited for this report: https://github.com/python/typeshed/issues.

Describe the bug

In github CI/CD we are running pyright with the following versions now:

Collecting pyright
  Downloading pyright-1.1.292-py3-none-any.whl (16 kB)
Collecting nodeenv>=1.6.0
  Downloading nodeenv-1.7.0-py2.py3-none-any.whl (21 kB)

Our pyright all of a sudden (since today I would say) now fails with the following traceback.

Link: https://github.com/keylime/keylime/actions/runs/4078266552/jobs/7028280605

/usr/local/lib/python3.11/site-packages/nodeenv.py:26: DeprecationWarning: 'pipes' is deprecated and slated for removal in Python 3.13
  import pipes
 * Install prebuilt node (19.6.0) .Incomplete read while readingfrom https://nodejs.org/download/release/v19.6.0/node-v19.6.0-linux-x64.tar.gz
.
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 1519, in <module>
    main()
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 1104, in main
    create_environment(env_dir, args)
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 980, in create_environment
    install_node(env_dir, src_dir, args)
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 739, in install_node
    install_node_wrapped(env_dir, src_dir, args)
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 762, in install_node_wrapped
    download_node_src(node_url, src_dir, args)
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 602, in download_node_src
    with ctx as archive:
  File "/usr/lib64/python3.11/contextlib.py", line 137, in __enter__
    return next(self.gen)
           ^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/nodeenv.py", line 573, in tarfile_open
    tf = tarfile.open(*args, **kwargs)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/tarfile.py", line 1630, in open
    saved_pos = fileobj.tell()
                ^^^^^^^^^^^^
AttributeError: 'bytes' object has no attribute 'tell'
Traceback (most recent call last):
  File "/usr/local/bin/pyright", line 8, in <module>
    sys.exit(entrypoint())
             ^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/cli.py", line 81, in entrypoint
    sys.exit(main(sys.argv[1:]))
             ^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/cli.py", line 21, in main
    return run(*args, **kwargs).returncode
           ^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/cli.py", line 38, in run
    npx = node.version('npx')
          ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/node.py", line 118, in version
    proc = run(target, '--version', stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/node.py", line 97, in run
    binary = _ensure_available(target)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/node.py", line 36, in _ensure_available
    return Binary(path=_ensure_node_env(target), strategy=Strategy.NODEENV)
                       ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pyright/node.py", line 63, in _ensure_node_env
    _install_node_env()
  File "/usr/local/lib/python3.11/site-packages/pyright/node.py", line 90, in _install_node_env
    subprocess.run(args, check=True)
  File "/usr/lib64/python3.11/subprocess.py", line 571, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/usr/bin/python3', '-m', 'nodeenv', '/tmp/pyright-python.root/env']' returned non-zero exit status 1.
Error: Process completed with exit code 1.

Node version check is dodgy

Node dumps all sorts of garbage when you run npx.CMD --version, you can't assume it is a version number alone.

 cmd.exe "/c pyright"
2021-08-06 13:16:24,473 - DEBUG - pyright.node - Checking for global target binary: npm
2021-08-06 13:16:24,490 - DEBUG - pyright.node - Found global binary at: C:\Program Files\nodejs\npm.CMD
2021-08-06 13:16:24,490 - DEBUG - pyright.node - Global binary exists at: C:\Program Files\nodejs\npm.CMD
2021-08-06 13:16:24,490 - DEBUG - pyright.node - Running node command with args: ['C:\\Program Files\\nodejs\\npm.CMD', 'info', 'pyright', 'version']
2021-08-06 13:16:26,547 - DEBUG - pyright.node - Version check for pyright returning (node:21540) ExperimentalWarning: The fs.promises API is experimental
2021-08-06 13:16:26,547 - DEBUG - pyright.node - Checking for global target binary: npx
2021-08-06 13:16:26,560 - DEBUG - pyright.node - Found global binary at: C:\Program Files\nodejs\npx.CMD
2021-08-06 13:16:26,561 - DEBUG - pyright.node - Global binary exists at: C:\Program Files\nodejs\npx.CMD
2021-08-06 13:16:26,561 - DEBUG - pyright.node - Running node command with args: ['C:\\Program Files\\nodejs\\npx.CMD', '--version']
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\matth\AppData\Local\Programs\Python\Python38\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\matth\.virtualenvs\search_service-3Tw2H1cF\Scripts\pyright.exe\__main__.py", line 7, in <module>
  File "c:\users\matth\.virtualenvs\search_service-3tw2h1cf\lib\site-packages\pyright\cli.py", line 37, in entrypoint
    sys.exit(main(sys.argv[1:]))
  File "c:\users\matth\.virtualenvs\search_service-3tw2h1cf\lib\site-packages\pyright\cli.py", line 19, in main
    return run(*args, **kwargs).returncode
  File "c:\users\matth\.virtualenvs\search_service-3tw2h1cf\lib\site-packages\pyright\cli.py", line 29, in run
    npx = node.version('npx')
  File "c:\users\matth\.virtualenvs\search_service-3tw2h1cf\lib\site-packages\pyright\node.py", line 121, in version
    info = tuple(int(value) for value in output.splitlines()[0].split('.'))
  File "c:\users\matth\.virtualenvs\search_service-3tw2h1cf\lib\site-packages\pyright\node.py", line 121, in <genexpr>
    info = tuple(int(value) for value in output.splitlines()[0].split('.'))
ValueError: invalid literal for int() with base 10: '(node:10820) ExperimentalWarning: The fs'

matth@DESKTOP-FANFFGU MINGW64 ~/public_record/search_service (CPRS-2036-build-script)
$ npx --version
(node:3388) ExperimentalWarning: The fs.promises API is experimental
7.13.0

Raise warning if new pyright version is detected

Currently we just naively use the latest version (unless PYRIGHT_PYTHON_FORCE_VERSION is set), this can reveal new type errors which while this can be good the majority of the time it can be problematic in CI where dependencies should be pinned to a specific version for reproducibility.

We shouldn't automatically upgrade to the latest pyright version but should instead print a warning specifying how to upgrade.

We probably need #8 and #19 (or #23) first before we can support this so that we can store the target pyright version in the config and add a flag to update to the latest version (or use a specific version).

NPM update message causing crashes

The version check for pyright will sometimes return the npm update message as well causing us to run a node command like

['/usr/local/bin/npx', '--yes', '[email protected]\nnpm notice \nnpm notice New minor version of npm available! 7.16.0 -> 7.20.3\nnpm notice Changelog: <https://github.com/npm/cli/releases/tag/v7.20.3>\nnpm notice Run `npm install -g [email protected]` to update!\nnpm notice ']

Add supported python versions to README

Only by digging into the tox.ini file I found out that python 3.7+ is required to run pyright; is it an idea to add this piece of information to the README?

Enable running pyright with older versions

When there's a new version of pyright available, running pyright checker will produce a warning and end with non-zero exit code:

image

While this warning is helpful in letting users know that there's a newer version and they should update, this makes it very hard to use pyright-python in an automated way, since it'd require explicitly setting PYRIGHT_PYTHON_FORCE_VERSION environment variable to the version of pyright we want to use (i.e. the version of the pyright-python package we have installed) which we'd need to be obtaining manually.

I think that while this warning is helpful and it should stay there, it really shouldn't block pyrighr completely and cause non-zero exit code. This is simply necessary because even though repositories should be updating their dependencies, not all repos can be expected to simply update the minute a new version comes out, realistically it will take a while for the repo to update, and during that time, all CI tests would be failing everywhere, since pyright-python doesn't even allow running old pyright versions, unless specified explicitly, even though it is versioned to represent which pyright version should it install and run.

prebuilt node binary is always downloaded even after the second run

context microsoft/pyright#4656

Environment

  • OS: Windows 11, WSL2, Debian 11
  • Python: 3.11.1

Description

Since 1.1.293 pyright-python always downloads and install prebuilt node binary even after the second run.

Expected behaviour

It won't re-download node binary after the second run.

How to reproduce

  1. ensure node is not in PATH
  2. create a venv `python3.11 -m venv --upgrade-deps venv
  3. install pyright-python newer than 1.1.293 ./venv/bin/pip install pyright=1.1.294
  4. run pyright twice ./venv/bin/pyright x2

log of 1.1.292

du at du-thinkbook in ~/workspace/pyright_test
$ time ./venv/bin/pyright --version
WARNING: there is a new pyright version available (v1.1.292 -> v1.1.294). 
Please install the new version or set PYRIGHT_PYTHON_FORCE_VERSION to `latest`

pyright 1.1.292
./venv/bin/pyright --version  1.55s user 0.16s system 76% cpu 2.246 total

du at du-thinkbook in ~/workspace/pyright_test
$ time ./venv/bin/pyright --version
WARNING: there is a new pyright version available (v1.1.292 -> v1.1.294).
Please install the new version or set PYRIGHT_PYTHON_FORCE_VERSION to `latest`

pyright 1.1.292
./venv/bin/pyright --version  1.50s user 0.22s system 103% cpu 1.669 total

log of 1.1.294

du at du-thinkbook in ~/workspace/pyright_test
$ time ./venv/bin/pyright --version
/home/du/workspace/pyright_test/venv/lib/python3.11/site-packages/nodeenv.py:26: DeprecationWarning: 'pipes' is deprecated and slated for removal in Python 3.13
  import pipes
 * Install prebuilt node (19.6.1) ..... done.
pyright 1.1.294
./venv/bin/pyright --version  4.17s user 0.97s system 38% cpu 13.198 total

du at du-thinkbook in ~/workspace/pyright_test
$ time ./venv/bin/pyright --version
/home/du/workspace/pyright_test/venv/lib/python3.11/site-packages/nodeenv.py:26: DeprecationWarning: 'pipes' is deprecated and slated for removal in Python 3.13
  import pipes
 * Install prebuilt node (19.6.1) ..... done.
pyright 1.1.294
./venv/bin/pyright --version  4.40s user 1.10s system 47% cpu 11.487 total

Warning - file or directory -- does not exist

See microsoft/pyright#2527

Describe the bug

Getting a warning about file or directory -- does not exist.

[tool.pyright]
stubPath = "" # typings by default shows warning
exclude = ["/node_modules",
"
/pycache"
]
ignore = ["source/","build/"]

reportMissingImports = true
reportMissingTypeStubs = false

pythonVersion = "3.8.5"
pythonPlatform = "Linux"
Searching for source files
File or directory "C:\myprojectfolder--" does not exist.
Found 21 source files
VS Code extension or command-line

Command line. Pyright 0.0.11

Add LSP support

Currently trying to use this pyright install with nvim's native LSP support based on this configuration, but the default cmd value (cmd = { "pyright-langserver", "--stdio" }) doesn't exist and is not installed by installing this package. Modifying the default value to just pyright i.e. cmd = { "pyright"}, doesn't work.

I can't find where documentation on the executable pyright-langserver

The warning message for the new pyright version makes `--output-json` not valid JSON.

Running

pyright --outputjson | jq

used to work,
but now I get
parse error: Invalid numeric literal at line 926, column 8.

pyright --outputjson >> output.txt

shows that std out includes

WARNING: there is a new pyright version available (v1.1.224.post0).
Please install the new version or set PYRIGHT_PYTHON_FORCE_VERSION to `latest`

at the end (after the JSON output), which is messing up jq.

As a side note, I get this message even though I am on the latest (1.1.224.post0), so the only workaround at the moment seems to be to set that env variable.

Add tests

Need to add tests, not testing anything is a very bad idea.

I would normally add tests straight away but this is a very small project that I just want to make available to install as soon as possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.