Basic specification for Python language

Source: Internet
Author: User

One, the specification of the Python script:


#!/usr/bin/env python

#-*-Coding:utf-8-*-

Import Os,urllib,mysqldb,time,platform

Main ():

Pass

if __name__ = = "__main__":

Main ()


Two, each function corresponds to a function

This I think the most important, each function is to write a function, so that your script is clear and easy to understand, script other reuse This function is also convenient, the script is not redundant. It is not recommended that there are many functions inside a function, which makes the function modular.


Iii. references to system commands

Os.popen ("/sbin/ifconfig eth0"). Read ()


Iv. Exception Handling

Try

Pass

Except Exception,e:

Print E



Here is a get local IP address, from the database query the purpose of the IP, to connect a URL, determine whether the URL can be used, and write the log. We mainly talk about the common usage of Python operation database.


#!/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 () #查询出的结果是元组形式, tuples and lists are basically the same

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

sql = "Select Host,user from Mysql.user where host= '%s '"% Ip#python Execute SQL statement only one SQL statement at a time, only one at a time, if you write multiple strips separated by semicolons will be an error, If you have multiple SQL statements, you can write a few more SQL and Cursor.execute () to separate execution

Cursor.execute (SQL) #执行sql语句

#cursor. Executemany ("" "INSERT into Dist_sniffer.sniffer_order_day values (%s,%s,%s,%s,%s,%s,%s,%s,%s)" ", Values) # You can use this when performing a combination of inserting a database, where each%s represents a database field and values is a tuple or a list

AllData = Cursor.fetchall () #接收sql执行结果, if it is a write operation, this is not necessary.

#conn. Commit () If it is a write operation, this is required to 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 address, subnet mask, default gateway, 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 ()


This article is from the "Big Barren Sutra" blog, please be sure to keep this source http://2892931976.blog.51cto.com/5396534/1746274

Basic specification for Python language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.