Skip to content

Instantly share code, notes, and snippets.

@jpramosi
Created October 26, 2022 16:51
Show Gist options
  • Save jpramosi/e951820bb13e105d566f69b2376c40b2 to your computer and use it in GitHub Desktop.
Save jpramosi/e951820bb13e105d566f69b2376c40b2 to your computer and use it in GitHub Desktop.
This script will fix poetry imports from virtual environment for pylint and pylance linter.
# tested only on ubuntu21.04
import os
import sys
from ast import literal_eval
from configparser import ConfigParser
from glob import glob
from pathlib import Path
import fileinput
INIT_HOOK = """
import os
import sys
from ast import literal_eval
from configparser import ConfigParser
from glob import glob
from pathlib import Path
from pylint.config import find_pylintrc
parser = ConfigParser()
parser.read("pyproject.toml")
project_name = literal_eval(parser.get("tool.poetry", "name"))
virtual_package_paths = glob(os.path.join(str(Path().home(
)), f".cache/pypoetry/virtualenvs/{project_name}-*/lib/python*/site-packages"))
sys.path[:] = [x for x in sys.path if not "site-packages" in x]
for path in virtual_package_paths:
sys.path.append(path)
sys.path.append(os.path.dirname(find_pylintrc()))
"""
def main():
parser = ConfigParser()
parser.read("pyproject.toml")
project_name = literal_eval(parser.get("tool.poetry", "name"))
try_glob = os.path.join(str(Path().home(
)), f".cache/pypoetry/virtualenvs/{project_name}-*/lib/python*/site-packages")
paths = glob(try_glob)
if len(paths) == 0:
print(
f"Could not find poetry`s virtual package path:\n\n\t'{try_glob}'")
return
virtual_package_path = paths[0]
init_hook_entry = ""
lines = INIT_HOOK.splitlines(False)
for line in lines:
if line == "" or line.isspace():
continue
line = line.replace("\"", "'")
init_hook_entry += f"{line}; "
init_hook_replace = f"init-hook = \"{init_hook_entry}\"\n"
if Path(".pylintrc").exists():
print("Update '.pylintrc'")
for line in fileinput.input(".pylintrc", inplace=True):
if not line.startswith("#") and init_hook_entry != "" and "init-hook" in line:
line = init_hook_replace
init_hook_entry = ""
sys.stdout.write(line)
else:
print("Create '.pylintrc'")
with open(".pylintrc", "wt", encoding="utf-8") as f:
f.write(f"[MASTER]\n{init_hook_replace}")
if Path(".vscode/settings.json").exists():
print(
f"File '.vscode/settings.json' already contains 'python.analysis.extraPaths'. You can manually add\n\n\t\"{virtual_package_path}\",\n")
else:
print("Create '.vscode/settings.json'")
Path(".vscode").mkdir(parents=True, exist_ok=True)
with open(".vscode/settings.json", "wt", encoding="utf-8") as f:
f.write(
f"{{\n \"python.analysis.extraPaths\": [\"{virtual_package_path}\"]\n}}\n")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment