mac下vscode配置python mac用vscode写python_mac下vscode配置python



文章目录

  • 关于 VS Code
  • 配置 Python 运行环境
  • 安装 python 插件
  • 搜索、安装 code runner
  • 调试
  • 配置解释器环境
  • 配置C运行环境
  • 远程开发
  • 其他配置
  • 添加配置文件(launch.json)解决 ModuleNotFoundError 的问题
  • 窗口显示完整路径
  • user snippets 快捷代码块
  • 进入 `python.json`
  • 添加多组配置
  • 添加代码头部
  • word wrap 自动换行
  • 自动补全函数的括号
  • 不再打开上次的编辑界面
  • 显示 matplotlib 图片
  • 参考



macOS 使用交流 QQ 群:658095824,V : ez-code


关于 VS Code

下载地址:https://code.visualstudio.com


VS Code 是一款方便好用的IDE,有丰富的插件;轻量级,跨 macOS、linux、windows 平台
macOS 的安装包,大小为 291.4MB (Pycharm 1GB),可以发现它基于 electron 开发。相比 pycharm,它的内存占用远远地小。

mac下vscode配置python mac用vscode写python_vscode_02


macOS 上的 VSCode

  • /Users/luyi/.vscode 插件安装地址
  • /Users/luyi/Library/Application\ Support/Code 缓存等数据
  • /Users/luyi/Library/Application\ Support/Code/User/snippets/python.json python 快捷代码

整编译器不是多有技术含量的事,但不同的开发环境,还是需要花点力气了解,才能熟练上手。废话不多说,这里介绍下基本的使用,后续会更新其他常用操作等。


配置 Python 运行环境

创建 Python 工作目录和文件

记得文件加 .py 后缀名

mac下vscode配置python mac用vscode写python_python_03


安装 python 插件

选中文件,点击运行时,会自动提示去安装 Python 插件

mac下vscode配置python mac用vscode写python_json_04


在弹出的插件中,选择 python,点击 install 即可

mac下vscode配置python mac用vscode写python_macos_05


搜索、安装 code runner

这个插件可以更方便的运行代码,可见这篇介绍:https://www.sohu.com/a/296509369_791833

mac下vscode配置python mac用vscode写python_mac下vscode配置python_06


右击选择扩展设置

mac下vscode配置python mac用vscode写python_json_07


b 站博主推荐以下设置

mac下vscode配置python mac用vscode写python_json_08


一一改成他推荐的设置

mac下vscode配置python mac用vscode写python_python_09


点击右上方 三角形 即可运行

mac下vscode配置python mac用vscode写python_macos_10


调试

在文件左侧,行号旁边,点击可以打断点;

点击左侧第四个按钮,点击 运行和调试,然后选择 python 文件,即可进入调试状态;

上方会悬浮有 六个按钮的小工具栏,可以进行单步调试。

mac下vscode配置python mac用vscode写python_macos_11


配置解释器环境

py文件空白处 右击,选择 Command Palette

mac下vscode配置python mac用vscode写python_json_12


键入 python:select

mac下vscode配置python mac用vscode写python_json_13


键入我的 python 解释器路径,然后选择

mac下vscode配置python mac用vscode写python_json_14


点击左下角,也会弹出上述 选择解释器 的窗口,可以再次键入选择。

mac下vscode配置python mac用vscode写python_python_15


选择 Run Python File In Terminal 即可看到用上述解释器,执行代码;

下次点击三角run 按钮,还是会使用 Run Python File In Terminal 这个模式;即记录上一次的模式;

mac下vscode配置python mac用vscode写python_macos_16


点击 Run Code 会使用原来的解释器

mac下vscode配置python mac用vscode写python_macos_17



配置C运行环境

参考:


1、安装插件
创建文件夹,然后创建 main.c 文件,然后点击右侧 调试 按钮:
如果只是创建 .c 文件,用 vscode 打开,不会产生这样的配置;

mac下vscode配置python mac用vscode写python_python_18


会弹出:

mac下vscode配置python mac用vscode写python_vscode_19

点击 Find C extension , 安装插件

mac下vscode配置python mac用vscode写python_vscode_20


2、创建配置文件 launch.jsontasks.json 再次点击调试按钮,会弹出菜单,选择 C++(GDB/LLDB)

mac下vscode配置python mac用vscode写python_json_21


选择默认配置

mac下vscode配置python mac用vscode写python_vscode_22


会生成一个launch.json文件

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) 启动",
            "type": "cppdbg",
            "request": "launch",
            "program": "输入程序名称,例如 ${workspaceFolder}/a.out",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb", 
        }
    ]
}

修改 program, externalConsole, preLaunchTask 键

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
          	// 配置名称,将会在启动配置的下拉菜单中显示
            "name": "(lldb) 启动",
          	// 配置类型,这里只能为cppdbg
            "type": "cppdbg",
	          // 请求配置类型,可以为launch(启动)或attach(附加) 
            "request": "launch",
	          // 将要进行调试的程序的路径
            "program": "${workspaceFolder}/a.out",
	          // 程序调试时传递给程序的命令行参数,一般设为空即可
            "args": [],
	          // 设为true时程序将暂停在程序入口处,一般设置为false  
            "stopAtEntry": false,
	          // 调试程序时的工作目录,一般为${workspaceRoot}即代码所在目录 
            "cwd": "${fileDirname}",
            "environment": [],
	          // 调试时是否显示控制台窗口,一般设置为true显示控制台  
            "externalConsole": true,
            "MIMode": "lldb", 
            "preLaunchTask": "echo"

        }
    ]
}

在 launch.json 页面,点击 command + shift + B,点击下方选项

mac下vscode配置python mac用vscode写python_vscode_23


点击从模板创建 tasks.json 文件

mac下vscode配置python mac用vscode写python_python_24


选择 Others

mac下vscode配置python mac用vscode写python_python_25


此时生成一个tasks.json文件

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "type": "shell",
            "command": "echo Hello"
        }
    ]
}

修改如下:
此处的 label 和上方的 preLaunchTask 一致

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo", 
            "type": "shell",
            "command": "gcc",
            "args": [
                "main.c",

            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "new",
                "showReuseMessage": true,
                "clear": false
            }
        }
    ]
}

3、运行

mac下vscode配置python mac用vscode写python_vscode_26


会调用系统终端,第一次使用需要授权

mac下vscode配置python mac用vscode写python_python_27



远程开发

1、安装插件 Remote Development

mac下vscode配置python mac用vscode写python_vscode_28


2、修改设置

Command + , 打开设置面板,输入关键词来查询

mac下vscode配置python mac用vscode写python_vscode_29


3、添加远程配置

安装完插件后左下角会出现一个绿色的图标;

点击选择会在命令窗口弹出几个选项,选择 Connect to Host – Configure SSH Host –

mac下vscode配置python mac用vscode写python_json_30


mac下vscode配置python mac用vscode写python_vscode_31


点击后,会打开 ~/.ssh/config 文件,内容如下

Host alias
    HostName hostname
    User user

我改为自己需要远程的 IP 地址和登录名

Host 55
    HostName 10.0.102.55
    User xx

4、连接

再次点击左下角绿色按钮,再次选择 Connect to Host,这时会出现刚设置的 host,比如我的 55

mac下vscode配置python mac用vscode写python_mac下vscode配置python_32


连接中,需要输入密码

mac下vscode配置python mac用vscode写python_vscode_33


点击打开,可以选择远程主机上的文件夹

mac下vscode配置python mac用vscode写python_json_34


在打开的文件中编写,远程主机上的文件就会发生改变。



其他配置


添加配置文件(launch.json)解决 ModuleNotFoundError 的问题

如果工程目录有多级,在子目录中引用另一个子目录的内容,即使增加了 sys.path,在 VSCode 中可能依然会会报 ModuleNotFoundError 问题(PyCharm 则不会)
根据查询,这是VSCode 的问题,增加 launch.json 设置 env 可以解决这个问题。方式如下:

mac下vscode配置python mac用vscode写python_mac下vscode配置python_35


点击添加配置

会在项目目录下生成 .vscode 目录,目录下有 launch.json 文件

mac下vscode配置python mac用vscode写python_macos_36


增加 env 和 envFile 两个键即可

{
    // 使用 IntelliSense 了解相关属性。 
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "env": {"PYTHONPATH":"${workspaceRoot}"},
            "envFile": "${workspaceRoot}/.env",
        }
    ]
}

窗口显示完整路径

mac下vscode配置python mac用vscode写python_macos_37


mac下vscode配置python mac用vscode写python_python_38


可以看到原来的设置为:

${activeEditorShort}${separator}${rootName}

activeEditorShort 改为 activeEditorMedium

如果需要显示完整路径,则改为 activeEditorLong

完整即:

${activeEditorLong}${separator}${rootName}

user snippets 快捷代码块

进入 python.json

比如 pycharm 中输入 main 的时候,会自动补全 main 函数,vscode 中则需要手动设置。

mac下vscode配置python mac用vscode写python_vscode_39


会在主窗口弹出这样的 sheet

列表中有众多语言,输入 py 选择 python 即可;


mac下vscode配置python mac用vscode写python_vscode_40


会进入 python.json 的编辑页面

这个文件位于 ~/Library/Application Support/Code/User/snippets/python.json


初始内容如下:

{
	// Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
}

添加多组配置

原有内容不改动,增加 pymain 的配置;结果如下

{
	// Place your snippets for python here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }

	"py1":{
      "prefix": "pymain",
      "body": [
        "if __name__ == '__main__':",
        "    ",
      ],
      "description": "python–main"
	},

	"py2":{
		"prefix": "prt",
		"body": [
			"print('')", 
		],
		"description": "print fuction"
	}

}

保存即可生效


在编辑器键入 pymain 的时候,即可出现提示,回车即可键入

mac下vscode配置python mac用vscode写python_macos_41


添加代码头部

参考:

pycharm 中可以设置创建 py 文件时,自动添加头部信息,vscode 目前没发现这个功能,我们也可以用 user snippets 来快捷添加头部信息。这里还可以使用一些变量,如:

"HEADER": {
		"prefix": "header",
		"body": [
			"#!/usr/bin/env python",
			"# -*- encoding: utf-8 -*-",
			"'''",
			"@File    :   $TM_FILENAME",
			"@Time    :   $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
			"@Author  :   Allen Mike",
			"@Version :   1.0",
			"@Contact :   wsjjfal@126.com",
			"@Desc    :   None",
			"'''",
			"",
			"",
			"$0"
		],
	}

出现效果为:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   csd.py
@Time    :   2021/10/28 15:54:07
@Author  :   Allen Mike
@Version :   1.0
@Contact :   wsjjfal@126.com
@Desc    :   None
'''

你可以根据需要,修改这个代码段,更多变量和使用方法可见:


word wrap 自动换行

进入设置,搜索 wrap,在 Editor : Word Wrap 选择 bounded;

Command + ,

mac下vscode配置python mac用vscode写python_python_42


自动补全函数的括号

进入 settings.json 文件(我的位于 ~/Library/Application\ Support/Code/User/settings.json
添加如下行:

"python.analysis.completeFunctionParens": true,

不再打开上次的编辑界面

打开 vs code 一般会自动打开上次关闭程序前,打开的文件
只是设置 window 还不够。
如果之前的文件过大,可能还会导致程序崩溃。

此时可以查看这个文件的 openedWindows 键,或者输入你的文件名。
/Users/luyi/Library/Application\ Support/Code/User/globalStorage/storage.json

删除文件名对应的 item,然后重启 VS Code,应该会有效果。


Linux 地址:
~/.config/Code/User/globalStorage/storage.json


显示 matplotlib 图片

输入 matplotlib 相关代码后,在编辑框内,右键–选择 Run Current File in Interactive Window , 右侧将会出现窗口,显示图片。
中文为:在交互式窗口中运行此文件

import matplotlib.pyplot as plt

squares = [1, 4, 9, 16, 25] 
fig, ax = plt.subplots() 
ax.plot(squares) 
plt.show()

mac下vscode配置python mac用vscode写python_mac下vscode配置python_43


参考



伊织 2021-10-26 22:31