这个问题真是烦, 花了我半天时间才解决. 结果原因是一个很小的问题,但是平常被忽略了, 网上找了半天貌似都和我的情况不一样.
好吧,言归正传.
代码:
定时每30秒查询一次当前端口的并发量并记录在文档里面
import os
from threading import Thread
def check_count():
while True:
msg = os.popen(‘netstat -nat |grep 9995 |wc -l’)
count = msg.read()
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(’/home/opvis/transfer_server/log/check_count.log’, ‘a’) as f:
f.write(current_time + ‘, 当前时间的并发访问量为:’ + count)
time.sleep(30)
t = Thread(target=check_count)
t.setDaemon(True)
t.start()
运行后虽然结果会正常执行, 但在终端会一直报如下错误:
原因是上一个os.popen执行对象没有关闭. 循环执行下一次os.popen就会出现该错误
修改如下后,不再显示该错误.
def check_count():
while True:
msg = os.popen(‘netstat -nat |grep 9995 |wc -l’)
count = msg.read()
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(’/home/opvis/transfer_server/log/check_count.log’, ‘a’) as f:
f.write(current_time + ‘, 当前时间的并发访问量为:’ + count)
msg.close()
time.sleep(30)
t = Thread(target=check_count)
t.setDaemon(True)
t.start()