文件打开和写入,无法获得执行

时间:2018-05-03 21:17:59

标签: python python-2.7

我正在尝试优雅地处理请求过多跟踪内存的情况,导致内存分配失败。这是我的python脚本,它已从主脚本中提取并简化为此问题(20秒睡眠只是为了让我可以观察内存分配和free -m的自由步骤):

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
from __future__ import print_function
from datetime import datetime
import subprocess
import os
import time
import re
import site
import signal
import sys
import getopt
import Gnuplot
from numpy import *
from decimal import *

def set_trace_buffer_size():
    """ Set trace buffer size """

    try:
       open('/sys/kernel/debug/tracing/buffer_size_kb'
                 , 'w').write(memory)
       print('path is via the non-exception route ')
    except:
        print('IO error setting trace buffer size ')
        sys.exit(2)

def free_trace_buffer():
    """ Free the trace buffer memory """

    try:
       open('/sys/kernel/debug/tracing/buffer_size_kb'
                 , 'w').write("1")
    except:
        print('IO error freeing the trace buffer memory ')
        sys.exit(2)

def signal_handler(signal, frame):
    print('  SIGINT: Forcing cleanup before exit.')
    # Free the memory
    free_trace_buffer()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

memory = "2500000"

set_trace_buffer_size()

print('Sleeping for 20 seconds')
time.sleep(int(20))

free_trace_buffer()

我明白了:

$ sudo ./test.py
close failed in file object destructor:
IOError: [Errno 12] Cannot allocate memory
path is via the non-exception route
Sleeping for 20 seconds
^C  SIGINT: Forcing cleanup before exit.

我的问题是:我做错了什么,如何在分配失败时使用except路径?

我想我总是可以在返回后查看值,看看是否是要求的。失败后,它似乎恢复到之前的值。

1 个答案:

答案 0 :(得分:2)

刷新或关闭文件时会引发IOError异常。您的代码没有显式关闭文件(当文件对象被垃圾收集时它会被隐式关闭),因此您的代码没有得到异常。

改变这个:

try:
   open(..., 'w').write(...)
except:
   ...

对此:

try:
   with open(..., 'w') as fp:
       fp.write(...)
except:
   ...

你应该正确地抓住你的IOError

对于记录,此案例中的with块是以下的简写:

try:
   fp = open(..., 'w')
   try:
       fp.write(...)
   finally:
       fp.close()
except:
   ...

注意显式调用close()会引发异常。