Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22462

Vasudev Ram: A quick console ruler in Python

$
0
0
By Vasudev Ram

I've done this ruler program a few times before, in various languages.

Here is an earlier version: Rule the command-line with ruler.py!

This one is a simplified and also slightly enhanced version of the one above.

It generates a simple text-based ruler on the console.

Can be useful for data processing tasks related to fixed-length or variable-length records, CSV files, etc.

With REPS set to 8, it works just right for a console of 80 columns.

Here is the code:
# ruler.py
"""
Program to display a ruler on the console.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram - http://jugad2.blogspot.com
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
find the positions and lengths of fields in fixed- or variable-length
records in a text file, fields in CSV files, etc.
"""

REPS = 8

def ruler(sep=' ', reps=REPS):
for i in range(reps):
print str(i) + ' ' * 4 + sep + ' ' * 3,
print '0123456789' * reps

def main():

# Without divider.
ruler()

# With various dividers.
for sep in '|+!':
ruler(sep)

if __name__ == '__main__':
main()
And the output:
$ python ruler.py
0 1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
01234567890123456789012345678901234567890123456789012345678901234567890123456789
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 +
01234567890123456789012345678901234567890123456789012345678901234567890123456789
0 ! 1 ! 2 ! 3 ! 4 ! 5 ! 6 ! 7 !
01234567890123456789012345678901234567890123456789012345678901234567890123456789
You can also import it as a module in your own program:
# test_ruler.py
from ruler import ruler
ruler()
# Code that outputs the data you want to measure
# lengths or positions of, goes here ...
print 'NAME AGE CITY'
ruler()
# ... or here.
print 'SOME ONE 20 LON '
print 'ANOTHER 30 NYC '
$ python test_ruler.py
Output:
0 1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
NAME AGE CITY
0 1 2 3 4 5 6 7
01234567890123456789012345678901234567890123456789012345678901234567890123456789
SOME ONE 20 LON
ANOTHER 30 NYC

- Enjoy.

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new products and services.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Viewing all articles
Browse latest Browse all 22462

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>