VS Code 实用技巧:10 个提升效率的插件

💻 VS Code 实用技巧:10 个提升效率的插件

分享 10 个我在日常开发中常用的 VS Code 插件,提升开发效率。

📚 目录

1. Python(Microsoft)

推荐指数: ⭐⭐⭐⭐⭐
功能: Python 开发核心插件
安装: Ctrl+Shift+X → 搜索 Python
功能:

  • 智能提示
  • 调试支持
  • 代码导航
  • 格式化

2. Pylance(Microsoft)

推荐指数: ⭐⭐⭐⭐
功能: Python 智能语言服务
安装: Ctrl+Shift+X → 搜索 Pylance
功能:

  • 快速类型推断
  • 类型检查
  • 代码补全

3. GitLens

推荐指数: ⭐⭐⭐⭐
功能: Git 历史查看
安装: Ctrl+Shift+X → 搜索 GitLens
功能:

  • 代码作者追踪
  • 行级 Git 历史
  • 比较视图

4. Docker

推荐指数: ⭐⭐⭐⭐
功能: Docker 容器管理
安装: Ctrl+Shift+X → 搜索 Docker
功能:

  • 容器管理
  • 镜像管理
  • Dockerfile 编辑

5. REST Client

推荐指数: ⭐⭐⭐⭐
功能: API 测试
安装: Ctrl+Shift+X → 搜索 REST Client
功能:

  • 发送 HTTP 请求
  • 保存请求历史
  • 环境变量

6. ESLint

推荐指数: ⭐⭐⭐
功能: JavaScript 代码检查
安装: Ctrl+Shift+X → 搜索 ESLint
功能:

  • 代码规范检查
  • 自动修复
  • 实时提示

7. Markdown All in One

推荐指数: ⭐⭐⭐⭐
功能: Markdown 编辑
安装: Ctrl+Shift+X → 搜索 Markdown All in One
功能:

  • 实时预览
  • 目录生成
  • 表格格式化

8. Project Manager

推荐指数: ⭐⭐⭐
功能: 项目管理
安装: Ctrl+Shift+X → 搜索 Project Manager
功能:

  • 保存项目列表
  • 快速切换项目
  • 项目标签

9. TODO Highlight

推荐指数: ⭐⭐⭐
功能: TODO 高亮
安装: Ctrl+Shift+X → 搜索 TODO Highlight
功能:

  • TODO 高亮
  • TODO 列表
  • 跳转 TODO

10. Better Comments

推荐指数: ⭐⭐⭐
功能: 注释高亮
安装: Ctrl+Shift+X → 搜索 Better Comments
功能:

  • 注释颜色区分
  • 优先级标记
  • 快速识别

🎯 总结

  • Python:核心插件
  • Pylance:智能提示
  • GitLens:Git 历史
  • Docker:容器管理
  • REST Client:API 测试
  • ESLint:代码检查
  • Markdown All in One:Markdown 编辑
  • Project Manager:项目管理
  • TODO Highlight:TODO 高亮
  • Better Comments:注释高亮

关注我,获取更多 VS Code 实用技巧!

Docker 实用技巧:10 个提升效率的命令

🐳 Docker 实用技巧:10 个提升效率的命令

分享 10 个我在日常开发中常用的 Docker 实用技巧。

📚 目录

1. docker run:运行容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 运行容器
docker run nginx

# 后台运行
docker run -d nginx

# 端口映射
docker run -d -p 8080:80 nginx

# 挂载卷
docker run -d -v /host/path:/container/path nginx

# 环境变量
docker run -d -e ENV=production nginx

2. docker ps:查看容器

1
2
3
4
5
6
7
8
9
10
11
# 查看运行中的容器
docker ps

# 查看所有容器
docker ps -a

# 查看特定容器
docker ps --filter "name=nginx"

# 查看容器 IP
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container-name

3. docker logs:查看日志

1
2
3
4
5
6
7
8
9
10
11
# 查看日志
docker logs container-name

# 实时查看
docker logs -f container-name

# 查看最近 100 行
docker logs --tail 100 container-name

# 查看指定时间后的日志
docker logs --since "2023-01-01" container-name

4. docker exec:执行命令

1
2
3
4
5
6
7
8
# 进入容器
docker exec -it container-name /bin/bash

# 执行命令
docker exec container-name ls /app

# 以特定用户执行
docker exec -u www-data container-name ls /app

5. docker build:构建镜像

1
2
3
4
5
6
7
8
9
10
11
# 构建镜像
docker build -t my-image:latest .

# 构建时指定 Dockerfile
docker build -f Dockerfile.prod -t my-image:prod .

# 构建时传递参数
docker build --build-arg ENV=production -t my-image:prod .

# 多阶段构建
docker build --target production -t my-image:prod .

6. docker-compose:编排容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 启动服务
docker-compose up -d

# 查看服务状态
docker-compose ps

# 查看日志
docker-compose logs -f

# 停止服务
docker-compose down

# 重启服务
docker-compose restart

7. docker volume:管理卷

1
2
3
4
5
6
7
8
9
10
11
# 创建卷
docker volume create my-volume

# 查看卷
docker volume ls

# 删除卷
docker volume rm my-volume

# 查看卷详细信息
docker volume inspect my-volume

8. docker network:管理网络

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建网络
docker network create my-network

# 查看网络
docker network ls

# 删除网络
docker network rm my-network

# 连接容器到网络
docker network connect my-network container-name

# 断开容器网络
docker network disconnect my-network container-name

9. docker image:管理镜像

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看镜像
docker images

# 删除镜像
docker rmi image-name

# 保存镜像
docker save -o my-image.tar my-image:latest

# 加载镜像
docker load -i my-image.tar

# 推送镜像
docker push my-image:latest

10. docker system:系统管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看系统信息
docker info

# 清理未使用的资源
docker system prune

# 清理所有未使用的资源
docker system prune -a

# 查看磁盘使用情况
docker system df

# 查看详细磁盘使用情况
docker system df -v

🎯 总结

  • docker run:运行容器
  • docker ps:查看容器
  • docker logs:查看日志
  • docker exec:执行命令
  • docker build:构建镜像
  • docker-compose:编排容器
  • docker volume:管理卷
  • docker network:管理网络
  • docker image:管理镜像
  • docker system:系统管理

关注我,获取更多 Docker 实用技巧!

Git 实用技巧:10 个提升效率的命令

🌿 Git 实用技巧:10 个提升效率的命令

分享 10 个我在日常开发中常用的 Git 实用技巧。

📚 目录

1. git status:查看状态

1
2
3
4
5
6
7
8
# 查看工作区状态
git status

# 简洁模式
git status -s

# 查看未跟踪文件
git status --untracked-files

2. git diff:查看差异

1
2
3
4
5
6
7
8
9
10
11
# 查看工作区与暂存区差异
git diff

# 查看暂存区与 HEAD 差异
git diff --cached

# 查看工作区与 HEAD 差异
git diff HEAD

# 查看特定文件差异
git diff file.py

3. git log:查看历史

1
2
3
4
5
6
7
8
9
10
11
# 查看提交历史
git log

# 图形化显示
git log --graph --oneline --all

# 查看特定文件历史
git log --follow file.py

# 查看特定作者提交
git log --author="Alice"

4. git checkout:切换分支

1
2
3
4
5
6
7
8
# 切换分支
git checkout main

# 创建并切换分支
git checkout -b feature

# 恢复文件
git checkout -- file.py

5. git branch:管理分支

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 列出分支
git branch

# 创建分支
git branch feature

# 删除分支
git branch -d feature

# 强制删除分支
git branch -D feature

# 重命名分支
git branch -m old-name new-name

6. git merge:合并分支

1
2
3
4
5
6
7
8
# 合并分支
git merge feature

# 合并时创建新提交
git merge --no-ff feature

# 解决冲突后继续
git merge --continue

7. git rebase:变基

1
2
3
4
5
6
7
8
9
10
11
# 变基
git rebase main

# 交互式变基
git rebase -i HEAD~3

# 解决冲突后继续
git rebase --continue

# 放弃变基
git rebase --abort

8. git stash:暂存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 暂存当前修改
git stash

# 查看暂存列表
git stash list

# 恢复暂存
git stash pop

# 恢复指定暂存
git stash apply stash@{0}

# 删除暂存
git stash drop stash@{0}

9. git reset:重置

1
2
3
4
5
6
7
8
9
10
11
# 重置暂存区(保留工作区)
git reset HEAD file.py

# 重置到指定提交
git reset --hard commit-hash

# 撤销提交(保留更改)
git reset --soft HEAD~1

# 撤销提交(丢弃更改)
git reset --hard HEAD~1

10. git cherry-pick:拣选

1
2
3
4
5
6
7
8
# �拣选提交
git cherry-pick commit-hash

# �拣选多个提交
git cherry-pick commit-hash1 commit-hash2

# 中断拣选
git cherry-pick --abort

🎯 总结

  • git status:查看状态
  • git diff:查看差异
  • git log:查看历史
  • git checkout:切换分支
  • git branch:管理分支
  • git merge:合并分支
  • git rebase:变基
  • git stash:暂存
  • git reset:重置
  • git cherry-pick:拣选

关注我,获取更多 Git 实用技巧!

Linux 安全加固:10 个提升安全性的技巧

🐧 Linux 安全加固:10 个提升安全性的技巧

分享 10 个我在生产环境中常用的 Linux 安全加固技巧。

📚 目录

1. 更新系统

1
2
3
4
5
6
# 更新系统
sudo apt update && sudo apt upgrade -y

# 自动安全更新
sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades

2. 配置防火墙

1
2
3
4
5
6
7
8
9
10
11
12
13
# 安装 UFW
sudo apt install ufw

# 基础配置
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

# 查看状态
sudo ufw status

3. 禁用 root 登录

1
2
3
4
5
6
7
8
9
# 编辑 SSH 配置
sudo nano /etc/ssh/sshd_config

# 修改以下配置
PermitRootLogin no
PasswordAuthentication no

# 重启 SSH 服务
sudo systemctl restart sshd

4. 使用 SSH 密钥

1
2
3
4
5
6
7
# 生成密钥
ssh-keygen -t ed25519 -C "your_email@example.com"

# 复制公钥到服务器
ssh-copy-id user@server

# 禁用密码登录(见第 3 步)

5. 配置 fail2ban

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 安装 fail2ban
sudo apt install fail2ban

# 复制配置文件
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# 编辑配置
sudo nano /etc/fail2ban/jail.local

# 添加自定义规则
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

# 启动 fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban

6. 限制 sudo 权限

1
2
3
4
5
6
7
8
# 添加用户到 sudo 组
sudo usermod -aG sudo username

# 编辑 sudoers
sudo visudo

# 添加权限
username ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

7. 启用 SELinux/AppArmor

1
2
3
4
5
6
7
# Ubuntu 使用 AppArmor
sudo apt install apparmor
sudo systemctl enable apparmor
sudo systemctl start apparmor

# 检查状态
sudo aa-status

8. 定期备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建备份脚本
sudo nano /usr/local/bin/backup.sh

# 添加以下内容
#!/bin/bash
tar -czf /backup/$(date +%Y%m%d).tar.gz /etc /var/www /home
find /backup -name "*.tar.gz" -mtime +30 -delete

# 添加执行权限
sudo chmod +x /usr/local/bin/backup.sh

# 添加定时任务
sudo crontab -e
0 0 * * * /usr/local/bin/backup.sh

9. 监控日志

1
2
3
4
5
6
7
8
9
10
11
12
# 安装 logwatch
sudo apt install logwatch

# 配置 logwatch
sudo nano /etc/logwatch/conf/logwatch.conf

# 设置每日邮件
MailTo = your_email@example.com
Detail = High

# 运行 logwatch
logwatch --detail High --mailto your_email@example.com

10. 安全审计

1
2
3
4
5
6
7
8
9
# 安装 auditd
sudo apt install auditd

# 添加审计规则
sudo auditctl -w /etc/passwd -p wa -k password_changes
sudo auditctl -w /etc/shadow -p wa -k shadow_changes

# 查看审计日志
sudo ausearch -k password_changes

🎯 总结

  • 更新系统
  • 配置防火墙
  • 禁用 root 登录
  • 使用 SSH 密钥
  • 配置 fail2ban
  • 限制 sudo 权限
  • 启用 SELinux/AppArmor
  • 定期备份
  • 监控日志
  • 安全审计

关注我,获取更多 Linux 实用技巧!

Linux 服务器优化:10 个提升性能的技巧

🐧 Linux 服务器优化:10 个提升性能的技巧

分享 10 个我在生产环境中常用的 Linux 服务器优化技巧。

📚 目录

1. 禁用不必要的服务

1
2
3
4
5
6
7
8
9
10
11
# 查看运行中的服务
systemctl list-units --type=service

# 禁用服务
sudo systemctl disable bluetooth
sudo systemctl disable cups
sudo systemctl disable ModemManager

# 停止服务
sudo systemctl stop bluetooth
sudo systemctl stop cups

2. 优化内核参数

1
2
3
4
5
6
7
8
9
10
11
12
# 编辑 sysctl.conf
sudo nano /etc/sysctl.conf

# 添加以下配置
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
vm.swappiness = 10

# 应用配置
sudo sysctl -p

3. 调整 swappiness

1
2
3
4
5
6
7
8
# 查看当前 swappiness
cat /proc/sys/vm/swappiness

# 临时调整
sudo sysctl vm.swappiness=10

# 永久调整(编辑 /etc/sysctl.conf)
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf

4. 使用 tmpfs

1
2
3
4
5
6
# 创建 tmpfs 目录
sudo mkdir -p /tmp/cache
sudo mount -t tmpfs -o size=1G tmpfs /tmp/cache

# 永久挂载(编辑 /etc/fstab)
echo "tmpfs /tmp/cache tmpfs defaults,size=1G 0 0" | sudo tee -a /etc/fstab

5. 优化文件系统

1
2
3
4
5
# 使用 ext4 优化挂载选项
sudo mount -o noatime,data=ordered /dev/sda1 /data

# 永久挂载(编辑 /etc/fstab)
/dev/sda1 /data ext4 noatime,data=ordered 0 0

6. 调整 TCP 参数

1
2
3
4
5
6
7
8
9
10
11
# 编辑 sysctl.conf
sudo nano /etc/sysctl.conf

# 添加以下配置
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_max_tw_buckets = 1440000

# 应用配置
sudo sysctl -p

7. 使用 SSD 优化

1
2
3
4
5
6
# 启用 TRIM
sudo fstrim -v /

# 永久启用(编辑 /etc/fstab)
# 添加 discard 选项
/dev/sda1 / ext4 defaults,discard 0 0

8. 优化 Docker 性能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 编辑 Docker 配置
sudo nano /etc/docker/daemon.json

# 添加以下配置
{
"storage-driver": "overlay2",
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
},
"live-restore": true
}

# 重启 Docker
sudo systemctl restart docker

9. 监控与告警

1
2
3
4
5
6
7
# 安装监控工具
sudo apt install htop iotop nethogs

# 安装 Prometheus + Grafana
# 使用 Docker 部署
docker run -d --name prometheus -p 9090:9090 prom/prometheus
docker run -d --name grafana -p 3000:3000 grafana/grafana

10. 定期维护

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 清理缓存
sudo apt clean
sudo apt autoremove

# 清理日志
sudo journalctl --vacuum-time=7d

# 定期任务(编辑 crontab)
sudo crontab -e

# 添加以下任务
0 0 * * * apt clean
0 1 * * * journalctl --vacuum-time=7d
0 2 * * * fstrim -v /

🎯 总结

  • 禁用不必要的服务
  • 优化内核参数
  • 调整 swappiness
  • 使用 tmpfs
  • 优化文件系统
  • 调整 TCP 参数
  • 使用 SSD 优化
  • 优化 Docker 性能
  • 监控与告警
  • 定期维护

关注我,获取更多 Linux 实用技巧!

Linux 命令行技巧:10 个提升效率的命令

🐧 Linux 命令行技巧:10 个提升效率的命令

分享 10 个我在日常运维中常用的 Linux 命令行技巧。

📚 目录

1. tmux:终端复用神器

1
2
3
4
5
6
7
8
9
10
11
# 安装 tmux
sudo apt install tmux

# 常用命令
tmux new -s mysession # 创建会话
tmux ls # 列出会话
tmux attach -t mysession # 连接到会话
Ctrl+b, c # 创建新窗口
Ctrl+b, % # 垂直分割
Ctrl+b, " # 水平分割
Ctrl+b, d # 分离会话

2. htop:进程监控

1
2
3
4
5
6
7
8
# 安装 htop
sudo apt install htop

# 常用命令
htop # 启动监控
F6 # 排序
F3 # 搜索进程
F9 # 结束进程

3. jq:JSON 处理

1
2
3
4
5
6
7
# 安装 jq
sudo apt install jq

# 常用命令
echo '{"name":"Alice","age":25}' | jq . # 格式化 JSON
curl -s https://api.example.com | jq .data # 提取数据
cat data.json | jq '.users[] | .name' # 提取字段

4. rg:超快文件搜索

1
2
3
4
5
6
7
8
9
# 安装 ripgrep
sudo apt install ripgrep

# 常用命令
rg "keyword" # 搜索关键词
rg "keyword" file.py # 搜索特定文件
rg -i "keyword" # 忽略大小写
rg --type python # 搜索 Python 文件
rg -l "keyword" # 只显示文件名

5. fzf:模糊搜索

1
2
3
4
5
6
7
# 安装 fzf
sudo apt install fzf

# 常用命令
fzf # 启动模糊搜索
Ctrl+R # 历史命令搜索(需配置)
Ctrl+T # 文件搜索(需配置)

6. curl:API 测试

1
2
3
4
5
6
# 常用命令
curl https://api.example.com # GET 请求
curl -X POST https://api.example.com -d "data" # POST 请求
curl -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com
curl -v https://api.example.com # 详细输出
curl -o output.json https://api.example.com # 保存到文件

7. netstat:网络监控

1
2
3
4
5
6
7
8
# 安装 netstat(或使用 ss)
sudo apt install net-tools

# 常用命令
netstat -tuln # 监听端口
netstat -an # 所有连接
netstat -r # 路由表
ss -tuln # ss 命令(netstat 替代)

8. rsync:文件同步

1
2
3
4
# 常用命令
rsync -avz source/ dest/ # 同步目录
rsync -avz user@server:/path/ ./ # 从远程同步
rsync -avz --delete source/ dest/ # 删除目标中多余的文件

9. awk:文本处理

1
2
3
4
5
# 常用命令
awk '{print $1}' file.txt # 打印第一列
awk -F',' '{print $1}' file.csv # 指定分隔符
awk '$3 > 100 {print $0}' file.txt # 条件筛选
awk '{sum += $1} END {print sum}' file.txt # 求和

10. sed:文本替换

1
2
3
4
5
# 常用命令
sed 's/old/new/g' file.txt # 替换文本
sed -i 's/old/new/g' file.txt # 直接修改文件
sed '2,5d' file.txt # 删除第 2-5 行
sed 's/^[[:space:]]*//' file.txt # 删除行首空格

🎯 总结

  • tmux:终端复用
  • htop:进程监控
  • jq:JSON 处理
  • rg:超快搜索
  • fzf:模糊搜索
  • curl:API 测试
  • netstat:网络监控
  • rsync:文件同步
  • awk:文本处理
  • sed:文本替换

关注我,获取更多 Linux 实用技巧!

Python 实用技巧:10 个提升效率的技巧

🐍 Python 实用技巧:10 个提升效率的技巧

分享 10 个我在日常开发中常用的 Python 实用技巧。

📚 目录

1. 列表推导式

1
2
3
4
5
6
7
# 传统写法
squares = []
for i in range(10):
squares.append(i * i)

# 列表推导式
squares = [i * i for i in range(10)]

2. f-string 格式化

1
2
3
name = "Alice"
age = 25
print(f"My name is {name}, I am {age} years old.")

3. collections 模块

1
2
3
4
5
6
7
8
9
10
11
from collections import Counter, defaultdict

# Counter 统计元素出现次数
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counter = Counter(words)
print(counter) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# defaultdict 默认值
d = defaultdict(int)
d["count"] += 1
print(d["count"]) # 1

4. with 语句

1
2
3
4
5
6
7
8
# 传统写法
file = open("data.txt", "r")
content = file.read()
file.close()

# with 语句(自动关闭文件)
with open("data.txt", "r") as file:
content = file.read()

5. *args 和 **kwargs

1
2
3
4
5
6
7
def func(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

func(1, 2, 3, name="Alice", age=25)
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 25}

6. 装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.2f} seconds")
return result
return wrapper

@timer
def slow_function():
import time
time.sleep(1)

slow_function() # slow_function took 1.00 seconds

7. contextlib

1
2
3
4
5
6
7
8
9
10
11
12
from contextlib import contextmanager

@contextmanager
def open_file(path, mode):
file = open(path, mode)
try:
yield file
finally:
file.close()

with open_file("data.txt", "r") as f:
content = f.read()

8. itertools

1
2
3
4
5
6
7
8
9
10
11
import itertools

# 无限迭代器
naturals = itertools.count(1)
print(next(naturals)) # 1
print(next(naturals)) # 2

# 组合
letters = ['A', 'B', 'C']
combinations = itertools.combinations(letters, 2)
print(list(combinations)) # [('A', 'B'), ('A', 'C'), ('B', 'C')]

9. typing 模块

1
2
3
4
5
6
from typing import List, Dict, Optional

def process_data(data: List[Dict[str, str]]) -> Optional[str]:
if not data:
return None
return data[0].get("name")

10. debugpy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 安装 debugpy
pip install debugpy

# 启动调试
import debugpy
debugpy.listen(("0.0.0.0", 5678))
debugpy.wait_for_client()

# 在 VS Code 中配置 launch.json
{
"name": "Python: Attach to Process",
"type": "python",
"request": "attach",
"connect": {
"host": "localhost",
"port": 5678
}
}

🎯 总结

  • 列表推导式:简洁高效
  • f-string:现代格式化
  • collections:实用数据结构
  • with:资源管理
  • *args/**kwargs:灵活参数
  • 装饰器:代码复用
  • contextlib:自定义上下文
  • itertools:迭代器工具
  • typing:类型提示
  • debugpy:远程调试

关注我,获取更多 Python 实用技巧!

Python 开发环境搭建:从零配置 VS Code + Python

🐍 Python Development Environment Setup: Configure VS Code + Python from Scratch

Step-by-step guide to configure Python development environment and improve development efficiency.

📚 Table of Contents

Prerequisites

  • Windows/macOS/Linux
  • Internet connection

Install Python

Windows

  1. Download Python from python.org
  2. Run installer (check “Add Python to PATH”)
  3. Verify installation:
1
2
python --version
pip --version

macOS

1
2
3
4
5
6
# Using Homebrew
brew install python

# Verify installation
python3 --version
pip3 --version

Linux (Ubuntu/Debian)

1
2
3
4
5
6
sudo apt update
sudo apt install python3 python3-pip

# Verify installation
python3 --version
pip3 --version

Install VS Code

Download from code.visualstudio.com

Configure VS Code for Python

  1. Open VS Code
  2. Install Python extension (search “Python” in Extensions)
  3. Open Command Palette (Ctrl+Shift+P)
  4. Select “Python: Select Interpreter”

Install Python Extensions

Recommended extensions:

  1. Python (Microsoft) - Core Python support
  2. Pylance (Microsoft) - Intelligent language service
  3. GitLens - Git history viewer
  4. Docker - Container management
  5. REST Client - API testing

Configure Python Interpreter

1
2
3
4
5
6
7
8
9
# Create virtual environment
python -m venv venv

# Activate
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windows

# Install packages
pip install requests

Test Your Setup

Create test.py:

1
2
print("Hello, Python!")
print("Environment configured successfully!")

Run with F5 or Ctrl+F5

Tips & Tricks

1. Use Virtual Environments

1
2
3
4
5
6
7
8
# Create
python -m venv venv

# Activate
source venv/bin/activate

# Deactivate
deactivate

2. Use Requirements.txt

1
2
3
4
5
# Generate requirements.txt
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

3. Use .env Files

1
2
3
4
5
6
7
8
9
# Install python-dotenv
pip install python-dotenv

# Create .env
echo "API_KEY=your_api_key" > .env

# Use in code
from dotenv import load_dotenv
load_dotenv()

4. Use VS Code Snippets

Create .vscode/python.code-snippets:

1
2
3
4
5
6
7
8
9
{
"Print to console": {
"prefix": "print",
"body": [
"print('$1')"
],
"description": "Print to console"
}
}

5. Use Debugging

Press F5 to debug your Python code.

Conclusion

Your Python development environment is now ready! Start building amazing projects!


Follow me for more Python tips and tricks!

Python 开发环境搭建:从零配置 VS Code + Python

🐍 Python 开发环境搭建:从零配置 VS Code + Python

本文手把手教你配置 Python 开发环境,从零开始打造高效开发体验。

📚 目录

安装 Python

Windows

  1. 下载 Python 3.12:https://www.python.org/downloads/
  2. 安装时勾选 Add Python to PATH
  3. 验证安装:
    1
    2
    python --version
    pip --version

macOS

1
2
3
4
5
6
# 使用 Homebrew
brew install python

# 验证安装
python3 --version
pip3 --version

Linux

1
2
3
4
5
6
7
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

# 验证安装
python3 --version
pip3 --version

安装 VS Code

  1. 下载 VS Code:https://code.visualstudio.com/
  2. 安装完成后打开

配置 VS Code Python 插件

1. 安装插件

打开 VS Code → 扩展(Ctrl+Shift+X)→ 搜索 Python

推荐插件:

  • Python(Microsoft) - 核心插件
  • Pylance(Microsoft) - 智能提示
  • Black Formatter - 代码格式化
  • isort - 导入排序

2. 配置 Python 解释器

  1. 打开命令面板(Ctrl+Shift+P)
  2. 输入 Python: Select Interpreter
  3. 选择你的 Python 解释器

3. 配置 settings.json

1
2
3
4
5
6
7
8
9
10
11
{
"python.defaultInterpreterPath": "/usr/bin/python3",
"python.linting.enabled": true,
"python.linting.pylintEnabled": false,
"python.linting.flake8Enabled": true,
"python.formatting.provider": "black",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
}
}

推荐插件

1. GitLens

  • 功能: Git 历史查看、代码作者追踪
  • 安装: Ctrl+Shift+X → 搜索 GitLens

2. Docker

  • 功能: 容器管理、Dockerfile 编辑
  • 安装: Ctrl+Shift+X → 搜索 Docker

3. REST Client

  • 功能: API 测试
  • 安装: Ctrl+Shift+X → 搜索 REST Client

4. Markdown All in One

  • 功能: Markdown 编辑、预览
  • 安装: Ctrl+Shift+X → 搜索 Markdown All in One

开发技巧

1. 代码片段

1
2
3
4
5
6
7
8
9
{
"Print to console": {
"prefix": "log",
"body": [
"print($0)"
],
"description": "Log output to console"
}
}

2. 快捷键

快捷键 功能
Ctrl+P 快速打开文件
Ctrl+Shift+F 全局搜索
Ctrl+Shift+P 命令面板
F5 启动调试
Ctrl+Shift+D 调试视图

调试配置

1. 创建 launch.json

  1. 打开调试视图(Ctrl+Shift+D)
  2. 点击齿轮图标
  3. 选择 Python

2. 基础配置

1
2
3
4
5
6
7
8
9
10
11
12
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

3. 高级配置

1
2
3
4
5
6
7
8
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/manage.py",
"args": ["runserver", "0.0.0.0:8000"],
"django": true
}

🎯 总结

  • 安装 Python + VS Code
  • 配置 Python 插件 + Pylance
  • 安装推荐插件(GitLens、Docker、REST Client)
  • 配置 settings.json(格式化、Linting)
  • 创建 launch.json(调试配置)

关注我,获取更多 Python 实用技巧!

Python 虚拟环境管理:venv vs pipenv vs poetry 对比

🐍 Python 虚拟环境管理:venv vs pipenv vs poetry 对比

本文详细对比 Python 虚拟环境管理工具,帮助开发者选择最适合的方案。

📚 目录

为什么需要虚拟环境

虚拟环境隔离项目依赖,避免版本冲突。

1
2
3
# 项目 A 需要 Django 3.2
# 项目 B 需要 Django 4.0
# 没有虚拟环境会冲突!

venv 详解

基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建虚拟环境
python -m venv venv

# 激活虚拟环境
# Linux/Mac
source venv/bin/activate
# Windows
venv\Scripts\activate

# 安装依赖
pip install requests

# 退出虚拟环境
deactivate

优缺点

优点 缺点
内置,无需安装 手动管理依赖
轻量级 无依赖锁定
快速 无项目配置

pipenv 详解

基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 安装 pipenv
pip install pipenv

# 创建项目
pipenv install requests

# 激活虚拟环境
pipenv shell

# 安装依赖
pipenv install django==3.2

# 退出虚拟环境
exit

优缺点

优点 缺点
自动创建虚拟环境 速度较慢
依赖锁定(Pipfile.lock) 功能较复杂
项目配置一体化 学习曲线陡峭

poetry 详解

基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 安装 poetry
pip install poetry

# 创建项目
poetry new my-project
cd my-project

# 添加依赖
poetry add requests
poetry add django==3.2

# 运行命令
poetry run python main.py

# 构建项目
poetry build

优缺点

优点 缺点
现代化设计 学习曲线陡峭
依赖解析强大 速度较慢
构建发布一体化 功能较重

工具对比

特性 venv pipenv poetry
内置
虚拟环境管理
依赖锁定
项目配置
构建发布
速度 ⚡ 快 🐢 慢 🐢 慢
学习曲线 ⬆️ 平缓 ⬆️ 中等 ⬆️ 陡峭

实战建议

新手推荐:venv + requirements.txt

  • 简单项目
  • 学习阶段
  • 快速原型

进阶推荐:poetry

  • 中大型项目
  • 团队协作
  • 需要构建发布

企业推荐:poetry + CI/CD

  • 生产环境
  • 自动化部署
  • 依赖安全审计

🎯 总结

  • venv: 轻量、快速、内置
  • pipenv: 功能全面、依赖锁定
  • poetry: 现代化、构建发布一体化

选择最适合你项目的工具!


关注我,获取更多 Python 实用技巧!