File size: 1,390 Bytes
c988237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/bin/bash

# Python 代码执行命令
PYTHON_CMD="python3 download_files.py"

# 最小剩余空间(单位:GB)
MIN_FREE_GB=3

# Python 进程 PID(初始为空)
PY_PID=""

# 启动 Python 代码的函数
start_python() {
    echo "启动 Python 脚本..."
    $PYTHON_CMD &
    PY_PID=$!
    echo "Python 运行中,PID=$PY_PID"
}

# 停止 Python 的函数
stop_python() {
    if [ -n "$PY_PID" ] && ps -p $PY_PID > /dev/null 2>&1; then
        echo "剩余空间不足,停止 python 进程 $PY_PID..."
        kill $PY_PID
        wait $PY_PID 2>/dev/null
        echo "Python 已停止"
    fi
}

# 获取剩余空间(GB)
get_free_space() {
    # 取根目录剩余空间,单位GB(取整数)
    df -BG / | awk 'NR==2{gsub("G",""); print $4}'
}

# --- 主流程 ---
start_python

while true; do
    sleep 900   # 等于 15 分钟(900 秒)

    free_space=$(get_free_space)
    echo "当前剩余空间:${free_space}GB"

    if [ "$free_space" -lt "$MIN_FREE_GB" ]; then
        stop_python
        echo "空间不足,脚本终止运行。"
        exit 0
    else
        echo "空间充足(>= ${MIN_FREE_GB}GB),继续监控..."
        # 如果 python 不小心崩了,也尝试重启
        if ! ps -p $PY_PID > /dev/null 2>&1; then
            echo "检测到 Python 已停止,重新启动..."
            start_python
        fi
    fi
done