23华软 python debug

2023年华为软件精英挑战赛,python语言,windows下在vscode实现调试。

文件目录树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
work
├── .vscode
| ├── launch.json
| └── tasks.json
├── Img
| └── 图片
├── maps
| ├── 1.txt
| ├── 2.txt
| ├── 3.txt
| └── 4.txt
├── src
| └── main.py
├── freeglut.dll
├── Robot_gui.exe
└── Robot.exe

vscode debug 配置

确保vscode已经安装python插件。

复制下面两个文件的内容。

launch.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"version": "0.2.0",
"configurations": [
{
"name": "dbg",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"justMyCode": true,
"preLaunchTask": "robot"
},
{
"name": "dbg_gui",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
},
"justMyCode": true,
"preLaunchTask": "robot_gui"
},
]
}

tasks.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
{
"version": "2.0.0",
"tasks": [
{
"label": "robot",
"type": "shell",
"command": "robot",
"isBackground": true,
"args": [
"-m", "maps/1.txt",
"python -m debugpy --listen 5678 src/main.py --wait",
"-d",
"-f",
"-l", "DBG"
],
// This task is run before some debug tasks.
// Problem is, it's a watch script, and since it never exits, VSCode
// complains. All this is needed so VSCode just lets it run.
"problemMatcher": [
{
"pattern": [
{
"regexp": ".",
"file": 1,
"location": 2,
"message": 3
}
],
"background": {
"activeOnStart": true,
"beginsPattern": ".",
"endsPattern": ".",
}
}
]
},
{
"label": "robot_gui",
"type": "shell",
"command": "robot_gui",
"isBackground": true,
"args": [
"-m", "maps/1.txt",
"python -m debugpy --listen 5678 src/main.py",
"-d",
"-l", "DBG"
],
// This task is run before some debug tasks.
// Problem is, it's a watch script, and since it never exits, VSCode
// complains. All this is needed so VSCode just lets it run.
"problemMatcher": [
{
"pattern": [
{
"regexp": ".",
"file": 1,
"location": 2,
"message": 3
}
],
"background": {
"activeOnStart": true,
"beginsPattern": ".",
"endsPattern": ".",
}
}
]
}
]
}


开始调试

打开main.py文件,设置断点(不清楚设置在哪里可以多设置几个),vscode选择运行和调试(ctrl+shift+F9) 开始调试(F9),会弹出错误提示框,点击取消,再次开始调试(F9),则成功进入调试界面。

调试界面有dbgdbg_gui,分别对应不带图形化界面和带图形化界面的调试。

踩坑

忘记设置断点

一直显示成功进入调试界面,就是不能操控,不能选择下一步和查看变量。

折腾了半天竟然是忘记打断点了,哭

初始几帧无法调试

由于需要再次启动debug,中间间隔时间内已经运行过几帧,比如最初判题器发送地图数据的过程无法调试。

可以在文件开头import time,然后在程序运行最开始if __name__ == '__main__':time.sleep(5),这样休眠一段时间,这些时间内attach上程序即可调试最初状态。

无法实现一键调试

已经是努力了很久找到的现在点两下调试的解决方案。

因为要attach上已经启动的程序,所以要先启动了程序,不想每次都输入一长串命令,就以task的方式,然而在launch中使用 preLaunchTask的方式会等待这个完成再开始调试,于是在task中用isBackgroundproblemMatcher属性实现了在调试的同时启动任务,这就导致并不能监听端口,正确的顺序应该是task启动一小段时间后去attach上,所以只能第一次没连接上报错,第二次再重新连接。

现在的也不是不能用,先这样吧,如有更优雅的解决方案希望可以交流一下。

联系作者

邮箱:781213930@qq.com

如遇到什么问题,或有什么想法想交流一下可以联系。