codekingpro/portable-devtools
115k
1"""Inspect a target Python interpreter virtual environment wise."""2 3from __future__ import annotations4 5import sys # built-in6 7 8def encode_path(value):9 if value is None:10 return None11 if not isinstance(value, (str, bytes)):12 value = repr(value) if isinstance(value, type) else repr(type(value))13 if isinstance(value, bytes):14 value = value.decode(sys.getfilesystemencoding())15 return value16 17 18def encode_list_path(value):19 return [encode_path(i) for i in value]20 21 22def run(): # noqa: PLR091223 """Print debug data about the virtual environment."""24 try:25 from collections import OrderedDict # noqa: PLC041526 except ImportError: # pragma: no cover27 # this is possible if the standard library cannot be accessed28 29 OrderedDict = dict # pragma: no cover # noqa: N80630 result = OrderedDict([("sys", OrderedDict())])31 path_keys = (32 "executable",33 "_base_executable",34 "prefix",35 "base_prefix",36 "real_prefix",37 "exec_prefix",38 "base_exec_prefix",39 "path",40 "meta_path",41 )42 for key in path_keys:43 value = getattr(sys, key, None)44 value = encode_list_path(value) if isinstance(value, list) else encode_path(value)45 result["sys"][key] = value46 result["sys"]["fs_encoding"] = sys.getfilesystemencoding()47 result["sys"]["io_encoding"] = getattr(sys.stdout, "encoding", None)48 result["version"] = sys.version49 50 try:51 import sysconfig # noqa: PLC041552 53 # https://bugs.python.org/issue2219954 makefile = getattr(sysconfig, "get_makefile_filename", getattr(sysconfig, "_get_makefile_filename", None))55 result["makefile_filename"] = encode_path(makefile())56 except ImportError:57 pass58 59 import os # landmark # noqa: PLC041560 61 result["os"] = repr(os)62 63 try:64 import site # site # noqa: PLC041565 66 result["site"] = repr(site)67 except ImportError as exception: # pragma: no cover68 result["site"] = repr(exception) # pragma: no cover69 70 try:71 import datetime # site # noqa: PLC041572 73 result["datetime"] = repr(datetime)74 except ImportError as exception: # pragma: no cover75 result["datetime"] = repr(exception) # pragma: no cover76 77 try:78 import math # site # noqa: PLC041579 80 result["math"] = repr(math)81 except ImportError as exception: # pragma: no cover82 result["math"] = repr(exception) # pragma: no cover83 84 # try to print out, this will validate if other core modules are available (json in this case)85 try:86 import json # noqa: PLC041587 88 result["json"] = repr(json)89 except ImportError as exception:90 result["json"] = repr(exception)91 else:92 try:93 content = json.dumps(result, indent=2)94 sys.stdout.write(content)95 except (ValueError, TypeError) as exception: # pragma: no cover96 sys.stderr.write(repr(exception))97 sys.stdout.write(repr(result)) # pragma: no cover98 raise SystemExit(1) # noqa: TRY200, B904 # pragma: no cover99 100 101if __name__ == "__main__":102 run()103 