IP address sorting in python practice series (02)
1. background note: The Virtual Machine ip addresses are obtained from the nova list of openstack, but these ip addresses are not sorted and grouped. To further enhance readability, sort the ip addresses in shell, you can use the sort command to perform the sorting operation. The specific operation is as follows:
[root@controller ~]# cat ip.txt | sort -t "." -k1,1n -k2,2n -k3,3n -k4,4n10.1.104.7510.1.104.8710.1.104.14910.1.104.15110.1.105.110.1.105.7
In the preceding method, IP addresses can be sorted. In the following python method, IP addresses can be sorted by carrying files. IP addresses are first read into a list, sort the IP addresses by using the sort () method in the list. script content
#! /Usr/bin/env python #-*-coding: utf8-*-''' author: Happyfrom: Happy cloud lab welcome to exchange ''' import sysimport OS. pathdef ipsort (filepath = "ip.txt"): ''' defines a function to sort IP addresses. The specified file is the ip.txt file in the current directory, and the list of sorted IP addresses is returned ''' try: ip = [] f = file (filepath, 'R') fcontext = f. readlines () for ips in fcontext: ips = ips. strip () ip. append (ips) ip. sort (lambda x, y: cmp (''. join ([I. must ust (3, '0') for I in x. split ('. ')]), ''. join ([I. rju St (3, '0') for I in y. split ('. ')]) # sort f. close () failed t Exception, msg: print "Error: % s" % (msg) sys. exit (1) return ipdef main (): ''' check whether the script carries parameters. A parameter-file name must be included and whether the file name exists. Call the sort function ipsort () '''try: if len (sys. argv )! = 2: print "Usage: % s" % (sys. argv [0], sys. argv [1]) else: if OS. path. exists (sys. argv [1]): filename = sys. argv [1] else: print "% s is not exists! "% (Sys. argv [1]) sys. exit (1) ip = ipsort (filename) # Run the sorting function to call for ips in ip: print ips failed t Exception, msg: print "\ 033 [31 mError: % s \ 033 [0 m "% (msg) if _ name _ =" _ main _ ": main ()
Note: The running mode is in the form of script + parameter. The test result is as follows:
[root@controller ~]# /usr/local/sbin/ipsort.py /root/ip.txt 10.1.104.7510.1.104.8710.1.104.22210.1.104.25010.1.105.110.1.105.7