Last active
February 2, 2025 13:58
-
-
Save jim-my/b81cffec7fba91fc578e9231b17242a4 to your computer and use it in GitHub Desktop.
Open given python module's source code in VSCode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import importlib | |
| import re | |
| import os.path | |
| import site | |
| import sys | |
| from typing import List, Optional | |
| def print_usage() -> None: | |
| print(f"Usage:\n\t{sys.argv[0]} MODULE_NAME") | |
| sys.exit(1) | |
| def run_shell_command(command: str) -> str: | |
| """Run a shell command and return its output""" | |
| print(f"> {command}") | |
| return os.popen(command).read() | |
| def get_module_candidates(name: str) -> List[str]: | |
| """Generate possible module name variations""" | |
| return [ | |
| name, | |
| name.replace("-", "_"), | |
| name.replace("-", "_").lower(), | |
| name.replace("-", ".").lower(), | |
| ] | |
| def import_module(name: str) -> Optional[object]: | |
| """Try to import module using different name variations""" | |
| for candidate in get_module_candidates(name): | |
| try: | |
| print(f"Try load module using: {candidate}") | |
| return importlib.import_module(candidate) | |
| except Exception as e: | |
| print(e) | |
| return None | |
| def get_module_path(module: object) -> tuple[str, str]: | |
| """Get module file and directory path""" | |
| module_file = re.sub(r"pyc$", "py", str(module.__file__)) | |
| module_dir = os.path.dirname(module_file) | |
| target = module_dir | |
| if os.path.isfile(module_file) and not module_file.endswith("__init__.py"): | |
| target = module_file | |
| return module_file, target | |
| def main(): | |
| if len(sys.argv) < 2: | |
| print_usage() | |
| module_name = sys.argv[1] | |
| # List matching modules using pip | |
| module_list = run_shell_command( | |
| f"pip3 list --format=columns| grep -i {module_name}" | |
| ) | |
| print(module_list) | |
| # Try to import the module | |
| my_module = import_module(module_name) | |
| if my_module: | |
| _, target = get_module_path(my_module) | |
| cmd = f"code {target}" | |
| print(f"> {cmd}") | |
| os.system(cmd) | |
| sys.exit(0) | |
| # If module not found, print package directories | |
| for pkg in site.getsitepackages(): | |
| print(pkg) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment