python语言规定_python 语言的基础规范

一、python 脚本的规范:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import os,urllib,MySQLdb,time,platform

main():

pass

if __name__ == "__main__":

main()

二、每一个功能对应一个函数

这一点我认为最重要,每一个功能就写一个函数,这样你的脚本清晰易懂,脚本其他复用这个功能也方便,脚本也不冗余。不建议不要一个函数里面有好多功能,使函数模块化。

三、系统命令的引用

os.popen("/sbin/ifconfig eth0").read()

四、异常处理

try:

pass

except Exception,e:

print e

以下是一个获取本地 ip 地址,从数据库查询 ip 的用途,去连接一个 URL,判断这个 URL 是否可以用,并写日志。主要讲了讲 python 操作数据库的常用用法。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import os,urllib,MySQLdb,time,platform

def log_w(text):

logfile = "/tmp/websocket.log"

if os.path.isfile(logfile):

if (os.path.getsize(logfile)/1024/1024) > 100:

os.remove(logfile)

now = time.strftime("%Y-%m-%d %H:%M:%S")

tt = str(now) + "\t" + str(text) + "\n"

f = open(logfile,'a+')

f.write(tt)

f.close()

def get_idcname(ip):

try:

conn = MySQLdb.connect(host = '192.168.8.43',port=3306,user = 'read_app',passwd = '123456',charset='utf8',connect_timeout=20)

cursor = conn.cursor()#查询出的结果是元组形式,元组和列表基本一样

#cursor = conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)#查询结果是字典形式

sql = "select host,user from mysql.user where host='%s'" % ip#python中执行sql语句一次只能是一个sql语句,一次只执行一条,如果用分号分开写多条的话是会报错的,如果是多条sql语句可以多写几个sql和cursor.execute()来分开执行

cursor.execute(sql)#执行sql语句

#cursor.executemany("""insert into dist_sniffer.sniffer_order_day values(%s,%s,%s,%s,%s,%s,%s,%s,%s) """,values)#执行组合插入数据库的时候可以用这个,每个%s代表一个数据库字段,values是一个元组或是一个列表

alldata = cursor.fetchall()#接收sql执行结果,如果是写操作的,这个就不用了

#conn.commit()如果是写操作,需要这个去提交

cursor.close()

conn.close()#关闭数据库回话

return alldata[0][0].encode('UTF8')#如果是写操作的话就没有返回值了。

except Exception,e:

return 0

def get_ip():

os = platform.system()

if os == "Linux":

ip = os.popen("/sbin/ifconfig eth0|grep 'inet addr'").read().strip().split(":")[1].split()[0]

elif os == "Windows":

import wmi

c=wmi.WMI()

network = c.Win32_NetworkAdapterConfiguration (IPEnabled=1)

for interface in network:

if interface.DefaultIPGateway:

ip = interface.IPAddress[0]

return ip

#print interface.IPAddress[0],interface.MACAddress,interface.IPSubnet[0],interface.DefaultIPGateway[0],interface.DNSServerSearchOrder[0],interface.DNSServerSearchOrder[1]

#获取出网的ip地址、MAC地址、子网掩码、默认网关、DNS

def web_status():

ip = get_ip()

idc_name = get_idcname(ip)

url = "http://www.text.com/index.php?idc_ip=%s&idc_name=%s" % (ip,idc_name)

get = urllib.urlopen(url)

if get.getcode() == 200:

aa = int(get.read().strip())

if aa == 1:

text = "Webservice return OK"

else:

text =  "Webservice return Error"

else:

text = "Conect webservice Error"

print text

log_w(text)

if __name__ == "__main__":

web_status()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值