我正在开发一个长时间运行的Python脚本,它会连接到许多不同的串口。脚本在执行几个小时后崩溃,提示“打开文件太多”。
我已经追踪了这个问题,发现是由于串口模块中的.close()方法似乎没有减少Python正在使用的文件描述符数目。我使用lsof | grep python | wc
来检查这一点。我使用的操作系统是Debian 7.2和Python 2.7.3。
下面的示例会逐渐使用更多的文件描述符,直到达到限制。为什么会出现这种情况,我应该如何避免它?
#!/usr/bin/env python
import serial #Used to communicate with pressure controller
import logging
import time
from time import gmtime, strftime
logging.basicConfig(filename="open_files_test.log")
# Write unusual + significant events to logfile + stdout
def log( message ):
time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
logging.warning( time + " " + message )
print( message )
for i in range(2000):
for n in range(1, 12):
try:
port_name = "/dev/tty" + str(n+20)
com = serial.Serial(port_name,9600,serial.EIGHTBITS,serial.PARITY_NONE,serial.STOPBITS_ONE,0.0,False,False,5.0,False,None)
com.open()
com.flushInput()
com.flushOutput()
log("Opened port: " + port_name)
except serial.SerialException:
com = None
log("could not open serial port: " + port_name)
com.close()
log("Closed port: " + port_name)
time.sleep(1)
log("Finished Program")
谢谢
com.close()
。 - jazzpi