ubuntu 关闭mysql进程_ubuntu10.04中的Python、MySQL和守护进程问题

在Ubuntu 10.04上,一个Python脚本通过while循环每2秒监控MySQL数据源。当从命令行运行时,脚本正常工作,但作为守护进程运行时,出现'MySQL server has gone away'的错误。尽管MySQL服务显示为运行状态,且能通过其他工具执行查询。问题可能涉及守护进程环境下的连接保持或超时设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我有一个在while循环中运行的脚本,每隔2秒监视一个mysql数据源。如果我从命令行运行If,它可以正常运行。但是如果我把它附加到一个守护进程,它会抛出一个错误,说“MySQL已经消失了”或者类似的东西。我检查了一下,发现MySQL正在运行。我甚至可以从其他工具执行查询。在

我急需帮助。我正在运行ubuntu10.04。在

错误代码Traceback (most recent call last):

File "/home/masnun/Desktop/daemon/daemon.py", line 67, in

main()

File "/home/masnun/Desktop/daemon/daemon.py", line 35, in main

USERPROG()

File "/home/masnun/Desktop/daemon/mymain.py", line 19, in main

cursor.execute("select * from hits_logs where id > '" + str(last) + "'")

File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute

self.errorhandler(self, exc, value)

File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defau$

raise errorclass, errorvalue

_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')

文件:守护进程

^{pr2}$

文件:守护程序.py在#!/usr/bin/env python

###########################################################################

# configure these paths:

LOGFILE = '/var/log/pydaemon.log'

PIDFILE = '/var/run/pydaemon.pid'

# and let USERPROG be the main function of your project

import mymain

USERPROG = mymain.main

###########################################################################

import sys, os

class Log:

"""file like for writes with auto flush after each write

to ensure that everything is logged, even during an

unexpected exit."""

def __init__(self, f):

self.f = f

def write(self, s):

self.f.write(s)

self.f.flush()

def main():

#change to data directory if needed

os.chdir("/home/masnun/Desktop/daemon")

#redirect outputs to a logfile

sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))

#ensure the that the daemon runs a normal user

os.setegid(1000) #set group first "pydaemon"

os.seteuid(1000) #set user "pydaemon"

#start the user program here:

USERPROG()

if __name__ == "__main__":

# do the UNIX double-fork magic, see Stevens' "Advanced

# Programming in the UNIX Environment" for details (ISBN 0201563177)

try:

pid = os.fork()

if pid > 0:

# exit first parent

sys.exit(0)

except OSError, e:

print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)

sys.exit(1)

# decouple from parent environment

os.chdir("/") #don't prevent unmounting....

os.setsid()

os.umask(0)

# do second fork

try:

pid = os.fork()

if pid > 0:

# exit from second parent, print eventual PID before

#print "Daemon PID %d" % pid

open(PIDFILE,'w').write("%d"%pid)

sys.exit(0)

except OSError, e:

print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)

sys.exit(1)

# start the daemon main loop

main()

文件:我的main.py在import MySQLdb

from ProxyChecker import ProxyChecker

from time import sleep

config = {"host":"localhost","username":"root","password":"masnun","database":"webtracc_db1"}

connection = MySQLdb.connect(config['host'],config['username'],config['password'],config['database'])

cursor = connection.cursor()

def main():

while True:

f = open("last","r")

last = f.read().strip()

f.close()

if last == '': last = 0;

last = int(last)

cursor.execute("select * from hits_logs where id > '" + str(last) + "'")

row = cursor.fetchall()

for x in row:

pc = ProxyChecker( x[2] )

pc.start()

last = x[0]

f = open("last","w")

f.write(str(last))

f.close()

sleep(2)

if __name__ == "__main__":

main()

File:

在代理检查器.py在#! /usr/bin/env python

from threading import Thread

from CheckProxy import CheckProxy

class ProxyChecker(Thread):

def __init__(self, data):

self.data = data

Thread.__init__(self)

def run(self):

pc = CheckProxy()

pc.check(self.data)

文件:CheckProxy.py在#! /usr/bin/env python

import MySQLdb

import socket

class CheckProxy:

def __init__(self):

self.config = {"host":"localhost","username":"root","password":"masnun","database":"webtracc_db1"}

self.portList = [80]

def check(self,host):

connection = MySQLdb.connect(self.config['host'],self.config['username'],self.config['password'],self.config['database'])

cursor = connection.cursor()

proxy = False

try:

for x in self.portList:

sock = socket.socket()

sock.connect((host,x))

#print "connected to: " + str (x)

sock.close()

cursor.execute("select count(*) from list_entries where list='1' and ip='"+ host + "' ")

data = cursor.fetchall()

#print data[0][0]

if data[0][0] < 1:

print 'ok'

proxy = True

except socket.error, e:

#print e

if proxy:

cursor.execute("insert into list_entries (ip,list) values ('"+ host.strip() +"','1') ")

else:

cursor.execute("insert into list_entries (ip,list) values ('"+ host.strip() +"','2') ")

if __name__ == "__main__":

print "Direct access not allowed!"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值