I have learned a lot about python recently. Today I will talk about the basics of python: the specification, indentation, and precautions for writing function functions of python scripts. These are my experiences in programming.
I. python script specifications:
Each script has its own specification. the following specifications are not mandatory, but the specification can make your script standardized, easy to understand, and easy to use.
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
This is written at the beginning and defines the script encoding. Currently, most of them are in UTF8 format. Therefore, you can use this encoding method to write scripts. You can use this encoding method to encode strings in Chinese. encoding is mainly performed by encode and decode.
Import OS, urllib, MySQLdb, time, platform
Import the required modules.
Main ():
Pass
Define functions
If _ name _ = "_ main __":
Main ()
This means that the script is executed from here. If other scripts call this script, this script will not execute other parts.
Tip: The above is the specification in the entire script. You should try to do this when writing the script.
Ii. python indentation
Python has strict indentation requirements. If indentation is incorrect, a syntax error is reported. In python, indentation is a tab key or four spaces, and four spaces are troublesome. It is easy to directly use a tab key, therefore, there is no special requirement. The tab key is generally used for indentation. Indentation is similar to layering, and the same indentation is the same level. See the following example:
If a = 0:
Print
Else:
Print B
3. Each function corresponds to a function.
I think it is most important to write a function for every function, so that your script is clear and easy to understand. It is also convenient to reuse other functions of the script, and the script is not redundant. It is not recommended that a function have many functions to modularize the function.
Iv. Reference of system commands
When referencing system commands, especially linux commands, you must write the full path of the command, for example:
OS. popen ("/sbin/ifconfig eth0"). read ()
You directly
OS. popen ("ifconfig eth0"). read ()
This is no problem, at least when you manually execute the script, it will be executed, but it will not be executed when the script is cron. So pay special attention to this.
V. Exception Handling
Try:
Pass
Except t Exception, e:
Print e
E indicates the error message. Try exception handling is enough for writing. There are other methods that are not commonly used.
The following is a method for obtaining a local ip address, querying the ip address usage from the database, connecting to a URL, determining whether the URL can be used and writing logs. This section describes the common usage of python for database operations.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 #! /Usr/bin/env python #-*-coding: UTF-8-*-importos, urllib, MySQLdb, time, platformdeflog_w (text): logfile = "/tmp/websocket. log "ifos. 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 () defget_idcname (ip): try: conn = MySQLdb. connect (host = '2017. 168.8.43 ', port = 3306, user ='re Ad_app ', passwd = '000000', charset = 'utf8', connect_timeout = 20) cursor = conn. cursor () # The query result is in the format of tuples, which is basically the same as the list # cursor = conn. cursor (cursorclass = MySQLdb. cursors. dictCursor) # The query result is in the dictionary format SQL = "select host, user from mysql. user where host = '% S' "cutefer (" "insert into dist_sniffer. Sniffer_order_day values (% s, % s) "", values) # This can be used for executing a combination of inserts into the database. Each % s represents a database field. values is a tuples or a list of alldata = cursor. fetchall () # receives the SQL Execution result. If it is a write operation, this will not be used # conn. commit () for write operations, you need to submit cursor. close () conn. close () # close the database session returnalldata [0] [0]. encode ('utf8') # if it is a write operation, no return value is returned. Extends texception, e: return0defget_ip (): OS = platform. system () ifos = "Linux": ip = OS. popen ("/sbin/ifconfig eth0 | grep 'inet addr '"). read (). strip (). split (":") [1]. split () [0] elifos = "Windows": importwmic = wmi. WMI () network = c. win32_NetworkAdapterConfiguration (IPEnabled = 1) forinterfaceinnetwork: ifinterface. defaultIPGateway: ip = interface. IPAddress [0] returnip # print interface. IPAddress [0], interface. MACAddress, interface. IPSubnet [0], interface. defaultIPGateway [0], interface. DNSServerSearchOrder [0], interface. DNSServerSearchOrder [1] # obtain the ip address, MAC address, subnet mask, default gateway, DNSdefweb_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) ifget. getcode () = 200: aa = int (get. read (). strip () ifaa = 1: text = "Webservice return OK" else: text = "Webservice return Error" else: text = "Conect webservice Error" printtextlog_w (text) if _ name __= = "_ main _": web_status ()
It is necessary to develop a good habit at the beginning, which will be very beneficial for later python programming. My deep understanding.