Practice One:
Use the WHO command to output information about all users who have logged in to the system and separate the login name, telex at login, logon time, and login address using regular expressions.
Format of the data:
%WHOWESC Console June 20:33wesc PTS/9 June to 01:38 (192.168.0.6) wesc pts/1 June 20 20:33 (: 0. 0) WeSC pts/2 June 20:33 (: 0.0) wesc PTS/4 June 20:33 (: 0.0) wesc PTS/3 June 20 20:33 (: 0.0) WESC PTS/5 June 20:33 (: 0.0) wesc PTS/6 June 20:33 (: 0.0) wesc PTS/7 June 20 20:33 (: 0.0 ) WeSC pts/8 June 20 20:33 (: 0.0)
Redirect the output of the WHO command to a file using Linux data redirection, and then analyze the file using Python.
Import ref = open (' Whodata.txt ', ' R ') for Eachline in F.readlines ():p rint re.split (R ' \s\s+ ', Eachline) f.close ()
You can see some of the problems that exist:
1. The end of each line has a carriage return symbol, to remove this thing.
2. There is also a tab \ t in the middle, which indicates that the regular expression of the design is to be modified.
3. To analyze the line directly from the terminal, do not save it as a local file for analysis.
Code Update:
#! /usr/bin/pythonfrom OS import popenfrom re import SPLITF = Popen (' Who ', ' R ') for Eachline in F.readlines (): print Split (R ' \s\s+|\t ', Eachline.strip ()) F.close ()
Where strip functions are described:
Function prototypes
declaration : S is a string, RM is a sequence of characters to be deleted
S.strip (RM) Remove the characters from the beginning and end of the s string in the RM delete sequence
S.lstrip (RM) Delete the character in the S string at the beginning of the RM delete sequence
S.rstrip (RM) Removes the character from the end of the S string that is located in the RM delete sequence
Note :
1. When RM is empty, the default is to remove the whitespace characters (including ' \ n ', ' \ R ', ' \ t ', ')
For example:
2. the RM delete sequence here is deleted as long as the character on the edge (beginning or end) is within the delete sequence .
For example:
Python Regular Expression Practice Chapter