Monday, May 19, 2014

Rule the command-line with!

By Vasudev Ram

While working at the command-line, I came up with the idea for this little Python utility which displays a ruler on the console. You can use this program's output as a ruler, to find the character positions and lengths of parts of your own program's output on the line, or to measure the lengths of fields in fixed-length or variable-length records in a text file or CSV file which you need to process via your program. And of course, your program can be in any language, not just Python.

Note: the program is written assuming a console width of 80 characters. You can change some of the values in it if you need it to work with a console of a different width.

I've called it Here is the code for it:
# - A program to display a ruler on the command line.
Copyright 2014 Vasudev Ram -
Program to display a line on the command-line screen.
The line consists of repeated occurrences of the characters:
0123456789, concatenated.
Purpose: By running this program, you can use its output as a ruler,
to find the position of your own program's output on the line, or to 
measure the lengths of fields in fixed- or variable-length records in a text file,  
fields in CSV files, etc.

import sys

def ruler(units="0123456789", repeats=8, fives=True):
    for i in range(repeats):
        if i < repeats - 1:
            if fives:
                sys.stdout.write(str(i) + (" " * 4) + "5" + (" " * 4))
                sys.stdout.write(str(i) + (" " * 9))
            if fives:
                sys.stdout.write(str(i) + (" " * 4) + "5" + (" " * 3))
                sys.stdout.write(str(i) + (" " * 8))
    #sys.stdout.write(units * repeats + "\n")
    sys.stdout.write(units * repeats)

def main():

if __name__ == "__main__":
And here is its output:
$ python
0    5    1    5    2    5    3    5    4    5    5    5    6    5    7    5
And the output from this call to ruler():
ruler(repeats=8, fives=False)
0         1         2         3         4         5         6         7
I've parameterized the values it uses, to some extent, so you can customize them. You can also import the file as a module and call its ruler() function in your own Python program. The code for doing that is as simple as:

from ruler import ruler

The Wikipedia article on rulers is interesting. So is the Golomb ruler. And here is a rolling ruler:

- Vasudev Ram - Dancing Bison Enterprises

Contact Page

1 comment:

Vasudev Ram said...

Oops, sorry, readers via Planet Python. I forgot to escape the HTML special characters like the less than sign (in the post), though I did use pre tags around the code. So in the Planet version of the post, there is a less than sign missing in the line just after the for loop:

for i in range(repeats):

That line should read:

if i "less-than" repeats - 1:

where I've used "less-than" to represent the actual sign itself.