1.StringIO Module
Stringio is used to read and write to a string buffer or to a memory file like a file.
f = Stringio () # Ready for writing
f = Stringio (BUF) # Ready for reading
F.close () # explicitly release resources held
Flag = F.isatty () # Always False
pos = F.tell () # get current position
F.seek (POS) # Set Current position
F.seek (pos, mode) # mode 0:absolute; 1:relative; 2:relative to EOF
BUF = F.read () # Read until EOF
BUF = F.read (n) # read up to n bytes
BUF = F.readline () # Read until end of line (' \ n ') or EOF
List = F.readlines () # List of f.readline () results until EOF
F.truncate ([size]) # truncate file at the most size (default:current POS)
F.write (BUF) # write at current position
F.writelines (list) # List:f.write (line)
F.getvalue () # return whole file ' s contents as a string
There are times when Python invokes a shell command or uses a socket to send a command to a port to return a string of branches. You can use Stringio to read and write these string branches.
For example, send the MNTR command to the zookeeper port
Import Sockets=socket.socket () s.connect (' localhost ', 2181) s.send (' Mntr ') data_mntr=s.recv (2048) s.close () print Data_mntr
# python test.py zk_version3.4.6-1569965, built on 02/20/2014 09:09 GMTZK_AVG_LATENCY0ZK_MAX_LATENCY0ZK_MIN_LATENCY0ZK _packets_received335zk_packets_sent334zk_num_alive_connections1zk_outstanding_requests0zk_server_ Statefollowerzk_znode_count17159zk_watch_count0zk_ephemerals_count1zk_approximate_data_size6666471zk_open_file _descriptor_count27zk_max_file_descriptor_count102400
The data returned by DATA_MNTR is a string buffer, and if you need to read and write each row of data, you need to use ReadLine () or ReadLines () as a file
#!/usr/bin/pythonimport socketfrom Stringio Import stringios=socket.socket ((' localhost ', s.connect) 2181 (' Mntr ') DATA_MNTR=S.RECV (2048) s.close () H=stringio (data_mntr) print h.readline () print h.readlines ()
# python test.py zk_version3.4.6-1569965, built on 02/20/2014 09:09 gmt[' zk_avg_latency\t0\n ', ' zk_max_latency\t0\n ', ' Zk_min_latency\t0\n ', ' zk_packets_received\t347\n ', ' zk_packets_sent\t346\n ', ' zk_num_alive_connections\t1\n ', ' ZK _outstanding_requests\t0\n ', ' zk_server_state\tfollower\n ', ' zk_znode_count\t17159\n ', ' zk_watch_count\t0\n ', ' Zk_ Ephemerals_count\t1\n ', ' zk_approximate_data_size\t6666471\n ', ' zk_open_file_descriptor_count\t27\n ', ' zk_max_ File_descriptor_count\t102400\n ']
2.cStringIO Module
The Cstringio module functions similarly to the Stringio module. However, this module is written in C language.
will be above the
From Stringio import Stringio
Switch directly to
From Cstringio import Stringio
Reference article:
Https://docs.python.org/2.6/library/stringio.html
This article is from the Linux SA John blog, so be sure to keep this source http://john88wang.blog.51cto.com/2165294/1745633
Python's Stringio module and Cstringio module