Skip to content

Commit 767e3ce

Browse files
Redirect stdout when checking imports. (#1007)
Fixes #1006 Also, set PYTHONNOUSERSITE so that the script doesn't even look in site packages when checking modules. Fix typo with capitilize.
1 parent b4a47a4 commit 767e3ce

2 files changed

Lines changed: 15 additions & 17 deletions

File tree

gazelle/std_modules.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,8 @@ func init() {
3737
cmd := exec.CommandContext(ctx, stdModulesScriptRunfile)
3838

3939
cmd.Stderr = os.Stderr
40-
cmd.Env = []string{}
41-
40+
// All userland site-packages should be ignored.
41+
cmd.Env = []string{"PYTHONNOUSERSITE=1"}
4242
stdin, err := cmd.StdinPipe()
4343
if err != nil {
4444
log.Printf("failed to initialize std_modules: %v\n", err)

gazelle/std_modules.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,28 @@
33
# it evaluates, it outputs true/false for whether the module is part of the
44
# standard library or not.
55

6-
import site
6+
import os
77
import sys
8-
9-
10-
# Don't return any paths, all userland site-packages should be ignored.
11-
def __override_getusersitepackages__():
12-
return ""
13-
14-
15-
site.getusersitepackages = __override_getusersitepackages__
8+
from contextlib import redirect_stdout
169

1710

1811
def is_std_modules(module):
19-
try:
20-
__import__(module, globals(), locals(), [], 0)
21-
return True
22-
except Exception:
23-
return False
12+
# If for some reason a module (such as pygame, see https://github.com/pygame/pygame/issues/542)
13+
# prints to stdout upon import,
14+
# the output of this script should still be parseable by golang.
15+
# Therefore, redirect stdout while running the import.
16+
with redirect_stdout(os.devnull):
17+
try:
18+
__import__(module, globals(), locals(), [], 0)
19+
return True
20+
except Exception:
21+
return False
2422

2523

2624
def main(stdin, stdout):
2725
for module in stdin:
2826
module = module.strip()
29-
# Don't print the boolean directly as it is captilized in Python.
27+
# Don't print the boolean directly as it is capitalized in Python.
3028
print(
3129
"true" if is_std_modules(module) else "false",
3230
end="\n",

0 commit comments

Comments
 (0)