Skip to content

Commit c110503

Browse files
authored
Merge pull request #60 from SublimeLinter/python-executable
Set `--python-executable` if inside a virtual environment
2 parents f6afbc8 + 808b0f8 commit c110503

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ Following is a list of *additional* settings specific to this linter:
4646
|cache-dir|The directory to store the cache in. Creates a sub-folder in your temporary directory if not specified. Set it to `false` to disable this automatic behavior, for example if the cache location is set in your mypy.ini file.|
4747
|follow-imports|Whether imports should be followed and linted. The default is `"silent"` for speed, but `"normal"` or `"skip"` may also be used.|
4848
|show-error-codes|Set to `false` for older mypy versions, or better yet update mypy.|
49+
|set-python-executable-inside-venv|Sets `--python-executable` if `VIRTUAL_ENV` is set as an environment variable. (Default: true)
4950

5051
All other args to mypy should be specified in the `args` list directly.
5152

linter.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import threading
2323
import getpass
2424

25+
import sublime
2526
from SublimeLinter.lint import LintMatch, PermanentError, PythonLinter
2627

2728

@@ -33,7 +34,8 @@
3334
class TemporaryDirectory(Protocol):
3435
name = None # type: str
3536

36-
37+
POSIX = sublime.platform() in ('osx', 'linux')
38+
BIN = 'bin' if POSIX else 'Scripts'
3739
USER = getpass.getuser()
3840
TMPDIR_PREFIX = "SublimeLinter-contrib-mypy-%s" % USER
3941

@@ -71,6 +73,8 @@ class Mypy(PythonLinter):
7173
"--show-error-codes": True,
7274
# Need this to silent lints for other files. Alternatively: 'skip'
7375
"--follow-imports": "silent",
76+
# Automatically set "--python-executable" if `VIRTUAL_ENV` is set
77+
"set-python-executable-inside-venv": True,
7478
}
7579

7680
def cmd(self):
@@ -122,6 +126,16 @@ def cmd(self):
122126
return cmd
123127

124128
def run(self, cmd, code):
129+
if (
130+
self.settings.get("set-python-executable-inside-venv")
131+
and (venv := self.get_environment().get("VIRTUAL_ENV"))
132+
and not cmd[0].startswith(venv)
133+
and not any(part.startswith("--python-executable") for part in cmd)
134+
and (py_executable := shutil.which("python", path=os.path.join(venv, BIN)))
135+
):
136+
idx = cmd.index("--no-pretty")
137+
cmd = cmd[:idx] + ["--python-executable", py_executable] + cmd[idx:]
138+
125139
with locks[self.get_working_dir()]:
126140
return super().run(cmd, code)
127141

0 commit comments

Comments
 (0)