Skip to content

Instantly share code, notes, and snippets.

@Kitsunetic
Created August 11, 2023 13:27
Show Gist options
  • Save Kitsunetic/5a93e55bbb4a8a50b7f5db2f988017a1 to your computer and use it in GitHub Desktop.
Save Kitsunetic/5a93e55bbb4a8a50b7f5db2f988017a1 to your computer and use it in GitHub Desktop.
reinstall vscode python extension
import json
import re
import shutil
import subprocess
from pathlib import Path
ext_dir = Path("/root/.vscode-server/extensions")
patterns = [
r"ms-python\.isort-\d{4}\.\d{1,2}\.\d{1,2}",
r"ms-python\.vscode-pylance-\d{4}\.\d{1,2}\.\d{1,2}",
r"ms-python\.python-\d{4}\.\d{1,2}\.\d{1,2}",
]
def is_matched(txt):
detected = False
for pattern in patterns:
if re.fullmatch(pattern, name):
detected = True
break
return detected
# Load db and remove detected extensions
new_db = []
with open(ext_dir / "extensions.json") as f:
for data in json.load(f):
name: str = data["relativeLocation"]
if is_matched(name):
print("Remove:", name)
ext_path = ext_dir / name
if ext_path.is_dir():
shutil.rmtree(ext_path, ignore_errors=True)
else:
new_db.append(data)
ext_names = [data["relativeLocation"] for data in new_db]
# Find obsolete extensions and remove
obsolete_ext_paths = []
for f in ext_dir.iterdir():
if f.name.startswith(".") or f.name == "extensions.json":
continue
elif f.name not in ext_names:
print("Remove:", f.name)
obsolete_ext_paths.append(f)
for f in obsolete_ext_paths:
shutil.rmtree(f, ignore_errors=True)
# Save new db
with open(ext_dir / "extensions.json", "w") as f:
json.dump(new_db, f)
# Reinstall Python extension
try:
print("Installing ms-python.python ...")
result = subprocess.run(["code", "--install-extension", "ms-python.python"], check=True, stdout=subprocess.PIPE)
result = subprocess.run(["code", "--install-extension", "ms-python.isort"], check=True, stdout=subprocess.PIPE)
print("Python extension installed successfully:", result.stdout.decode())
except subprocess.CalledProcessError as e:
print("An error occurred while installing the Python extension:", str(e))
except FileNotFoundError:
print(
"VS Code command 'code' not found. Make sure Visual Studio Code is installed and the 'code' command is added to your PATH."
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment