VScode python插件

1.LiveCode

从扩展商店安装完以后初次使用可能异常

要配置一下解释器的路径

设置(ctrl+,)-> 搜索 Livecode:Python Path

然后填解释器的路径

如果我们有循环或需要展示一些中间变量状态,就可以使用该插件,LiveCode主要拥有下面四个功能

实时评估:不需要运行Python脚本就可以查看各个变量的值

变量显示:每当声明或更改一个变量时,它的新值都会同时改变并显示

2在 VS Code 调试器中自动显示变量形状和维度信息

原文在这里

win下

复制代码
C:\Users\<你的用户名>\.vscode\extensions\ms-python.debugpy-<版本号>-win32-x64\bundled\libs\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_xml.py

linux下

复制代码
  ~/.vscode/extensions/ms-python.debugpy-*\bundled\libs\debugpy\_vendored\pydevd\pydevd_plugins\extensions\types/

修改 get_variable_details() 函数

打开 pydevd_xml.py 文件,找到get_variable_details()函数,完整修改之后如下

复制代码
def get_variable_details(val, evaluate_full_value=True, to_string=None, context: Optional[str] = None):
    """
    :param context:
        This is the context in which the variable is being requested. Valid values:
            "watch",
            "repl",
            "hover",
            "clipboard"
    """
    try:
        # This should be faster than isinstance (but we have to protect against not having a '__class__' attribute).
        is_exception_on_eval = val.__class__ == ExceptionOnEvaluate
    except:
        is_exception_on_eval = False

    if is_exception_on_eval:
        v = val.result
    else:
        v = val

    _type, type_name, resolver = get_type(v)
    type_qualifier = getattr(_type, "__module__", "")
    if not evaluate_full_value:
        value = DEFAULT_VALUE
    else:
        try:
            # 添加形状信息
            shape_info = ""
            try:
                # 处理 PyTorch Tensor
                if type_qualifier == "torch" and hasattr_checked(v, 'shape') and hasattr_checked(v, 'dtype'):
                    shape = tuple(v.shape)
                    dtype = str(v.dtype)
                    shape_info = f"{{Tensor: {shape}}} "
                # 处理 NumPy ndarray
                elif type_qualifier == "numpy" and hasattr_checked(v, 'shape') and hasattr_checked(v, 'dtype'):
                    shape = tuple(v.shape)
                    dtype = str(v.dtype)
                    shape_info = f"{{ndarray: {shape}}} "
                # 处理 Pandas DataFrame
                elif type_qualifier == "pandas.core.frame" and hasattr_checked(v, 'shape'):
                    shape = tuple(v.shape)
                    shape_info = f"{{DataFrame: {shape}}} "
                # 处理 Pandas Series
                elif type_qualifier == "pandas.core.series" and hasattr_checked(v, 'shape'):
                    shape = tuple(v.shape)
                    dtype = str(v.dtype)
                    shape_info = f"{{Series: {shape}}} "
                # 处理其他有 shape 属性的对象
                elif hasattr_checked(v, 'shape'):
                    shape_info = f"{{{v.shape}}} "
                # 处理可计数对象
                elif hasattr_checked(v, '__len__'):
                    try:
                        length = len(v)
                        # 对于字符串类型,只显示 {str} 而不显示长度
                        if type_name == "str":
                            shape_info = f"{{{type_name}}} "
                        else:
                            shape_info = f"{{{type_name}: {length}}} "
                    except:
                        pass
            except:
                pass
            
            str_from_provider = _str_from_providers(v, _type, type_name, context)
            if str_from_provider is not None:
                value = shape_info + str_from_provider

            elif to_string is not None:
                value = shape_info + to_string(v)

            elif hasattr_checked(v, "__class__"):
                if v.__class__ == frame_type:
                    value = pydevd_resolver.frameResolver.get_frame_name(v)

                elif v.__class__ in (list, tuple):
                    if len(v) > 300:
                        value = "%s: %s" % (str(v.__class__), "<Too big to print. Len: %s>" % (len(v),))
                    else:
                        value = "%s: %s" % (str(v.__class__), v)
                else:
                    try:
                        cName = str(v.__class__)
                        if cName.find(".") != -1:
                            cName = cName.split(".")[-1]

                        elif cName.find("'") != -1:  # does not have '.' (could be something like <type 'int'>)
                            cName = cName[cName.index("'") + 1 :]

                        if cName.endswith("'>"):
                            cName = cName[:-2]
                    except:
                        cName = str(v.__class__)

                    value = "%s: %s" % (cName, v)
            else:
                value = shape_info + str(v)
        except:
            try:
                value = repr(v)
            except:
                value = "Unable to get repr for %s" % v.__class__

    # fix to work with unicode values
    try:
        if value.__class__ == bytes:
            value = value.decode("utf-8", "replace")
    except TypeError:
        pass

    return type_name, type_qualifier, is_exception_on_eval, resolver, value

再重启即可

3 Better Comments

写注释的好帮手

它能根据关键词用不同的颜色高亮代码片段。支持以下类型的高亮:

感叹号 "!" 代码警告。

问号"?"代表存留疑问。

TODO 代码未来将要进行的操作。

@param 参数

此外,它还支持在设置中自定义需要高亮句子的首部关键词。

4 autoDocstring

写注释的好帮手

能够自动生成函数的注释格式,通过tab键快速切换填充块编写相应的注释。

Python Indent

python 自动缩进

相关推荐
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers