You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS EC2 t2.micro实例上Python进程无故终止问题求助

问题描述

在AWS t2.micro EC2实例上运行Python脚本,通过命令./myscript > /dev/null 2>&1 &启动,用ps -elf | grep python查看进程状态。但脚本运行数小时甚至数天后会无故终止,无法再通过该命令查到进程,无法确定是否因内存不足(OOM)等原因导致。

脚本功能:从Excel读取加密货币符号(如BTC),与kraken.com建立WebSocket连接收集数据,每小时将数据保存为.pkl文件。该脚本在本地Windows环境的Jupyter/Anaconda中运行无异常。

附脚本代码:

#!/usr/bin/python3

import json
from websocket import create_connection
import pandas as pd
import time
import requests
from datetime import datetime, timedelta

df = pd.read_excel('Kraken_All_pairs.xlsx')
kraken_pairs = ''
for i in df['Symbol']:
    kraken_pairs = kraken_pairs + '"' + str(i) + '/USD",'
kraken_pairs = kraken_pairs[0:-1]
kraken_pairs = '{"event":"subscribe", "subscription":{"name":"trade"}, "pair":[' + kraken_pairs + ']}'
lasttime = datetime.utcfromtimestamp(time.time()).strftime('%H')
while True:
    try:
        data_list = list()
        try:
            ws = create_connection("wss://ws.kraken.com/")
            ws.send(kraken_pairs)
        except Exception as e:
            time.sleep(1)
            break;
        while True:
            try:
                data_list.append(json.loads(ws.recv()))
            except Exception as e:
                timestamp_exception = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
                try:
                    ws = create_connection("wss://ws.kraken.com/")
                    ws.send(kraken_pairs)
                except Exception as e:
                    time.sleep(1)
                    break;
            now = datetime.utcfromtimestamp(time.time()).strftime('%H')

            if lasttime != now:
                lasttime = now
                break
                
        data_list = [value for value in data_list if value != {'event': 'heartbeat'}]
        data_list = [value for value in data_list if type(value) != dict]
        Pair = [value[3] for value in data_list]
        Price = [value[1][0][0] for value in data_list]
        Date = [value[1][0][2] for value in data_list]
        df_all = pd.DataFrame(list(zip(Pair, Price, Date)), columns =['Pair', 'Price', 'Date'])
        df_all['Date'] = df_all['Date'].astype(float)
        df_all['Date'] = df_all['Date']*1000
        df_all['Date'] = pd.to_datetime(df_all['Date'], unit='ms')
        df_all['Date'] = df_all['Date'].dt.strftime("%m.%d.%Y, %H:%M:%S")
        list_all_df_pairs = []
        for value in df_all['Pair'].unique():
            list_all_df_pairs.append(df_all.loc[df_all['Pair'] == value])
        for index in range(0,len(list_all_df_pairs)):
            path = './pkl/' + str((datetime.utcfromtimestamp(time.time()) - timedelta(hours=1)).strftime('%H')) + '_' + list_all_df_pairs[index]['Pair'].iloc[0].replace('/','_') + '.pkl'
            list_all_df_pairs[index].to_pickle(path)
    except Exception as e:
        timestamp_exception = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
排查步骤

1. 确认是否因内存不足被系统杀死

t2.micro仅配备1GB内存,极易出现OOM(内存不足)导致系统主动终止进程:

  • 查看系统OOM日志:执行dmesg | grep -i kill,若输出包含Out of memory: Killed process xxx (python3),则说明是内存不足问题。
  • 实时监控内存占用:用top或htop(需先通过sudo apt install htop安装)观察脚本运行时的内存变化;或设置定时任务记录内存状态,比如每5分钟执行free -h >> memory_log.txt。

2. 收集脚本运行日志

当前启动命令将所有输出丢弃到/dev/null,无法获取报错信息。修改启动命令,将日志保存到文件:

nohup ./myscript > script.log 2>&1 &

此命令会把标准输出和错误输出都写入script.log,进程终止后可查看日志定位具体错误(如WebSocket连接失败、文件写入权限问题等)。

3. 完善脚本异常日志记录

脚本中的try...except仅记录了异常发生的时间戳,未记录具体错误信息,无法定位问题。修改异常处理逻辑,将错误写入日志:

except Exception as e:
    timestamp_exception = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
    with open('error.log', 'a', encoding='utf-8') as f:
        f.write(f"{timestamp_exception}: {str(e)}\n")

这样能明确捕获到WebSocket重连失败、Excel读取错误、文件写入失败等具体问题。

4. 检查系统资源限制

WebSocket连接会占用文件描述符,若系统文件描述符限制过低,可能导致连接失败甚至进程终止:

  • 查看当前限制:执行ulimit -n。
  • 临时调整限制:执行ulimit -n 65535(仅对当前会话有效)。
  • 永久调整限制:编辑/etc/security/limits.conf,添加以下内容后重启系统:
* soft nofile 65535
* hard nofile 65535

5. 验证WebSocket连接稳定性

Kraken的WebSocket可能会主动断开连接,脚本当前的重连逻辑存在缺陷:重连失败后直接break,可能导致外层循环无法继续执行。建议增加重连重试次数,而非直接退出循环:

# 内层重连逻辑修改示例
retry_count = 0
max_retries = 5
while retry_count < max_retries:
    try:
        ws = create_connection("wss://ws.kraken.com/")
        ws.send(kraken_pairs)
        break
    except Exception as e:
        retry_count += 1
        timestamp_exception = datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')
        with open('error.log', 'a', encoding='utf-8') as f:
            f.write(f"{timestamp_exception}: 重连失败,重试次数 {retry_count}/{max_retries}: {str(e)}\n")
        time.sleep(2)
if retry_count >= max_retries:
    # 多次重连失败后,记录日志并回到外层循环
    with open('error.log', 'a', encoding='utf-8') as f:
        f.write(f"{datetime.utcfromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S.%f')}: 达到最大重连次数,无法恢复连接\n")
    continue
脚本优化建议
  1. 内存优化:t2.micro内存有限,data_list每小时会积累大量数据,处理完后主动清理内存:
# 处理完数据后添加以下代码
del data_list, df_all, list_all_df_pairs
import gc
gc.collect()
  1. 使用更健壮的WebSocket库:替换websocket库为websockets(异步库),它内置了重连机制和心跳检测,稳定性更高。
  2. 标准化日志系统:使用Python内置的logging模块替代手动写日志,支持分级日志、日志轮转等功能,更便于排查问题。
  3. 配置进程守护:用systemd创建服务,让系统在脚本终止后自动重启:
    • 创建服务文件/etc/systemd/system/kraken-data.service:
    [Unit]
    Description=Kraken Data Collection Service
    After=network.target
    
    [Service]
    User=ubuntu  # 替换为你的EC2用户名
    WorkingDirectory=/path/to/your/script  # 替换为脚本所在目录
    ExecStart=/usr/bin/python3 ./myscript
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
    
    • 启动并启用服务:
    sudo systemctl daemon-reload
    sudo systemctl start kraken-data.service
    sudo systemctl enable kraken-data.service
    
    • 查看服务日志:journalctl -u kraken-data.service -f

内容的提问来源于stack exchange,提问作者Charles1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:01:01