print "Hello World!"
>>> t=(1,2,[1,2]) >>> t[2] [1, 2]
list=[0, 1, 2, 3, 4, 5]
for item in list:
if item == 1:
print item
elif item in (2, 3, 4, 5):
print "aha " + str(item)
else:
pass
def func(var): some code here
class MyClass(object):
common = 1
def __init__(self):
self.myvariable = 5
def myfunction(self, arg1, arg2):
return self.myvariable
def some_function():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
else:
# Exception didn't occur, we're good.
pass
finally:
# This is executed after the code block is run
# and all exceptions have been handled, even
# if a new exception is raised while handling.
print "We're done with that."
import random from time import clock
yum install python-psycopg2
#get database connect def get_con(): host = '127.0.0.1' port = "5432" database = 'platform' user = 'postgres' password = 'postgres' conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port) return conn
#执行sql查询 def query(conn, sql): cursor = conn.cursor() cursor.execute(sql) results = cursor.fetchall() #close cursor cursor.close() return results
def getUsers():
conn = get_con()#open connect
sql = """select *
from t_user
order by intime DESC
limit 5"""
items = query(conn , sql)
print str(items)
conn.close() #close connect
#发送邮件
def send_email(subject, content):
sender = "yourmail@***.com"
password = "******" #密码是看不见的哦
receivers = [tq8117179#163.com] #本人真实邮箱,欢迎发邮件讨论技术问题
host = "smtp.exmail.qq.com"
port = 465
msg = MIMEText(content,'html','utf-8')
msg['From'] = sender
msg['To'] = ",".join(receivers)
msg['Subject'] = Header(subject, 'utf-8')
try:
smtp = smtplib.SMTP_SSL(host, port)
smtp.login(sender, password)
smtp.sendmail(sender, receivers, msg.as_string())
except Exception, e:
logger.error(e)
logger.info(content)
# coding=utf-8
import logging
import logging.handlers
logger = logging.getLogger('monitor')
logger.setLevel(logging.DEBUG)
filehandler = logging.handlers.TimedRotatingFileHandler(
"/mnt/log/monitor/monitor_log", 'midnight', 1, 7)
# 设置文件后缀名称
filehandler.suffix = "%Y%m%d.log"
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s: %(message)s')
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)
通过logging.getLogger(‘monitor')生成一个logger,然后配置一个文件处理器。
然后在我们监控程序中引用即可:
from log import logger
config = None
#get config
def getConfig():
global config
if config is None:
config = ConfigParser.ConfigParser()
config.read("monitor.ini")
return config
#get database connect
def get_con():
host = getConfig().get('db', 'host')
port = getConfig().get('db', 'port')
database = getConfig().get('db', 'database')
user = getConfig().get('db', 'user')
password = getConfig().get('db', 'password')
conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
return conn
#发送邮件
def send_email(subject, content):
sender = getConfig().get('mail', 'sender')
password = getConfig().get('mail', 'password')
receivers = getConfig().get('mail', 'receivers').split(",")
host = getConfig().get('mail', 'host')
port = getConfig().getint('mail', 'port')
msg = MIMEText(content,'html','utf-8')
msg['From'] = sender
msg['To'] = ",".join(receivers)
msg['Subject'] = Header(subject, 'utf-8')
try:
smtp = smtplib.SMTP_SSL(host, port)
smtp.login(sender, password)
smtp.sendmail(sender, receivers, msg.as_string())
except:
logger.exception("Exception: ")
logger.info(content)
#数据库配置 [db] host = 127.0.0.1 port = 5432 database = platform user = postgres password = postgres #邮件配置 [mail] sender = yourmail@XXX.com password = ****** #多个联系人用英文逗号隔开 receivers = tq8117179#163.com host = smtp.exmail.qq.com port = 465
start_time = "2015-10-1 16:24:24"
end_time = None
#update end_time, invoke before get new data
def update_end_time():
global end_time
now = time.mktime(datetime.now().timetuple())
end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now))
return end_time
#update end_time, invoke after get new data
def update_start_time():
global start_time
global end_time
start_time = end_time
return start_time
getUsers可以改写成:
def getUsers (conn):
global start_time
global end_time
sql = """select *
from t_user
where intime>=""" +"'"+start_time+"' and intime<"+"'"+end_time+"';"
items = query(conn, sql)
if items is not None and len(items)>0:
count = len(items)
tip = "又有"+str(count)+"个用户已经注册了。"+end_time
send_email(tip, tip+"\n"+str(items))
def task():
#init end_time and start_time, must init end_time first!!!
end_time = update_end_time()
start_time = update_start_time()
#init config
getConfig()
while True:
conn = get_con() #open connect
end_time = update_end_time()
############## process ##############
logger.info("query: "+end_time)
getUsers (conn)
#do some task else here
## end
update_start_time()
conn.close()#close connect
time.sleep(5*60)
#end of while
def run_monitor():
monitor = threading.Thread(target=task)
monitor.start()
if __name__ == "__main__":
run_monitor()
yum install python-setuptools
easy_install supervisor
echo_supervisord_conf > /etc/supervisord.conf
[program:monitor] command = python /usr/monitor/monitor.py directory = /usr/monitor user = root
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有