Posts

Showing posts with the label python

Real Tail'ing in Python

or, finding last few lines in a file. Ok. So, last solution was not perfect. It just returned last line from a file. What about returning say 10 or may be more lines? Here is the modified Tail function to do that: def Tail(filepath, nol=10, read_size=1024): """ This function returns the last line of a file. Args: filepath: path to file nol: number of lines to print read_size: data is read in chunks of this size (optional, default=1024) Raises: IOError if file cannot be processed. """ f = open(filepath, 'rU') # U is to open it with Universal newline support offset = read_size f.seek(0, 2) file_size = f.tell() while 1: if file_size offset = file_size f.seek(-1*offset, 2) read_str = f.read(offset) # Remove newline at the end if read_str[offset - 1] == '\n': read_str = read_str[:-1] lines = read_str.split('\n') if len(lines) >= nol: # Got nol lines ...

Tail'ing in Python

or, finding last line of a huge file.. How do you find the last line of a 2 GB log file from within your program? You don't want to go through the whole file, right? Right. What you want to do is, you want to start reading from end until you find a newline character. Here is how I did it in Python: def Tail(filepath, read_size=1024): """ This function returns the last line of a file. Args: filepath: path to file read_size: data is read in chunks of this size (optional, default=1024) Raises: IOError if file cannot be processed. """ f = open(filepath, 'rU') # U is to open it with Universal newline support offset = read_size f.seek(0, 2) file_size = f.tell() while 1: if file_size offset = file_size f.seek(-1*offset, 2) read_str = f.read(offset) # Remove newline at the end if read_str[offset - 1] == '\n': read_str = read_str[0:-1] lines = read_str.split('\n') ...

pyMailer: Sends Mails

This is one tool that I had written about one and half years back. Why am I talking about it now? Well, I have recently realized that it's quite a useful thing. I find myself using it quite a bit. You may also find it of some use. What does it do? As the title says, it just sends mails. To understand the usability, it will probably help to know why I wrote this? I wanted a tool to backup my files to my gmail account in quick and easy steps. I wanted to use gmail smtp server as I thought gmail would be reliable. Using gmail smtp was not easy, as it required login and tls support from the client. I know I could have used Thunderbird and other clients. But, idea was to have something simple and quick to use. So, requirements were like: 1. Definitely a command line interface 2. Platform independent (should run on linux and windows at least) 3. Attaching files should be easy and smooth. 4. Should have support for TLS 5. And possibly should have support for GUI and an option to save conf...