VSCode是MS推出的一款免费的开源并跨平台的轻量级代码编辑器,内置Git和Debug等经常使用功能,强大的插件扩展功能以及简单的配置几乎能够打形成任意编程语言的IDE。本文简单聊一下其本地attach和remote debug功能。html
默认在vscode中打开py文件能够直接使用断点调试,使用的Debug模式为:Python: Current File (Integrated Terminal),这是针对vscode中当前打开的文件。python
对于独立于vscode以外运行程序的debug,根据是否和vscode位于同一主机能够分为local attach和remote debug。编程
下面以python为例简单讲一下debug功能。json
实际使用根据须要下载最新版本便可。app
打开vscode工程目录下的.vscode/launch.json文件,添加以下内容:编程语言
{ "version": "0.2.0", "configurations": [ { "name": "Python: Local Attach", "type": "python", "request": "attach", "port": 12345, "host": "127.0.0.1", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] }, ] }
若是没有launch.json,新建一个便可,或者打开左侧debug view,选择打开launch.json,vscode会打开或者建立一个默认的json配置文件,而后将上面configurations列表中的内容复制到已有的launch.json中便可。编辑器
新建一个python脚本文件./Main.pypost
# -*- coding:utf-8 -*- import datetime, time # import VSCodeDebug import ptvsd host = "127.0.0.1" # or "localhost" port = 12345 print("Waiting for debugger attach at %s:%s ......" % (host, port)) ptvsd.enable_attach(address=(host, port), redirect_output=True) ptvsd.wait_for_attach() while True: time.sleep(1) cur_date = datetime.datetime.now() print cur_date
脚本中的host和port必须和launch.json中当前debug模式中host与port的值一致。url
ptvsd模块安装:python -m pip install --upgrade ptvsdspa
调试步骤以下:
注意:
结果以下:
远程调试可让咱们在本地使用vscode调试远程主机上运行的程序,而只须要在本地安装vscode。
在上面.vscode/launch.json文件"configurations"列表中加入下面的内容做为Remote Debug的配置:
{ "name": "Python: Remote Debug", "type": "python", "request": "attach", "port": 12345, // valid port in remote host "host": "1.2.3.4", // replace with your remote host IP "pathMappings": [ { "localRoot": "${workspaceFolder}", //the path of the folder opened in VS Code, can be replaced by real path, such as: "D:\\Projects\\Cnblogs\\Alpha Panda"
"remoteRoot": "~/demo" // Linux example; adjust as necessary for your OS and situation. } ] },
这里有两点须要注意:
远端脚本添加以下代码:
import ptvsd host = "1.2.3.4" # remote host ip port = 12345 # remote host valid port ptvsd.enable_attach(address=(host, port), redirect_output=True) ptvsd.wait_for_attach()
因为remote debug要求本地和远端程序的源代码必须一致,所以
本地脚本添加以下代码:
# import ptvsd # host = "1.2.3.4" # remote host ip # port = 12345 # remote host valid port # ptvsd.enable_attach(address=(host, port), redirect_output=True) # ptvsd.wait_for_attach()
此外,本地和远端都须要安装ptvsd模块。
这样启动远端的脚本程序,本地vscode添加断点,启用新加的Python: Remote Debug模式debug便可进入调试环境。
本地能够经过ptvsd来启动远端的程序:
python -m ptvsd --host 1.2.3.4 --port 12345 --wait -m myproject
通过上面操做,Debug 配置中有两种debug模式:
python插件默认会提供几种不一样的debug configs.
如Python: Django,Python: Flask等能够参考一下。
只有上面两种无法直接调试vscode中的文件,下面添加本地的debug 模式的配置:
{ "name": "Python: Current File (Integrated Terminal)", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" },
总之,vscode不管出身仍是功能以及美观简单易用性等都是无可挑剔的,常常使用sublime text的话,能够尝试一下vscode.
若是使用Pycharm进行python开发能够参考一下个人另外一篇博文:Pycharm远程调试原理及配置
参考:
https://code.visualstudio.com/docs/python/debugging
https://code.visualstudio.com/docs/editor/variables-reference