ToolkitX
知识库工具箱

自动化脚本

os, subprocess, paramiko

25min·进阶

01. os 与 pathlib

os 模块提供操作系统相关功能,pathlib 提供面向对象的路径操作。pathlib 是更现代的方式,推荐使用。
python
import os
from pathlib import Path

# pathlib 操作
current = Path(".")
print(current.resolve())

# 路径操作
file_path = Path("data/output.csv")
print(file_path.parent)    # data
print(file_path.suffix)    # .csv

# 创建和删除
Path("new_dir").mkdir(parents=True, exist_ok=True)
Path("file.txt").touch()
Path("file.txt").unlink()

# 遍历目录
for py_file in Path(".").rglob("*.py"):
  print(py_file)

02. subprocess 模块

subprocess 模块用于执行外部命令和程序。推荐使用 run() 函数。
python
import subprocess

# 执行简单命令
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)

# 执行 shell 命令
result = subprocess.run("echo $HOME", shell=True, capture_output=True, text=True)

# 检查返回码
result = subprocess.run(
["git", "status"],
capture_output=True,
text=True,
check=True
)

知识测验

1/5正确 0

pathlib 相比 os.path 的优势是什么?

下一节

单元测试

下一节