Skip to content

Instantly share code, notes, and snippets.

@gsw945
Created July 19, 2017 10:04
Show Gist options
  • Save gsw945/54d177f9b6ca9515dcdc733842b847b6 to your computer and use it in GitHub Desktop.
Save gsw945/54d177f9b6ca9515dcdc733842b847b6 to your computer and use it in GitHub Desktop.
show file content like Linux `cat` command but only show specified line
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import linecache
import sys
description= '''show file content like Linux `cat` command but only show specified lines'''
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-b', '--begin', type=int, help='begin range of lines (default: 1)')
parser.add_argument('-e', '--end', type=int, help='end range of lines (default: lines count of file)')
parser.add_argument('file', type=str, nargs='?', help='the file path')
args = parser.parse_args()
begin = getattr(args, 'begin', None)
end = getattr(args, 'end', None)
_file = getattr(args, 'file', None)
c_error = '\x1b[6;37;41m'
c_end = '\x1b[0m'
c_warning = '\x1b[7;30;43m'
def file_lines(path, begin, end=None):
lines = []
# way 1
i = begin
'''
with open(path) as f:
for index, line in enumerate(f):
if begin <= index + 1 <= end:
if i <= end:
lines.append(line)
i += 1
else:
break
'''
# way 2
#'''
while True:
line = linecache.getline(path, i)
if isinstance(end, int):
if i > end:
break
else:
if line == '':
break
i += 1
lines.append(line)
#'''
return lines
if _file is None:
parser.print_help()
else:
if os.path.exists(_file):
if begin is None:
begin = 1
if isinstance(end, int):
if begin > end:
print('Error: {0}`begin` is greater than `end`{1}'.format(c_error, c_end))
sys.exit(0)
lines = file_lines(_file, begin, end)
print(''.join(lines), end='')
else:
print('Error: {0}file `{1}` not exist{2}'.format(c_error, _file, c_end))
print('{0}{1}{2}'.format(c_warning, '=' * 60, c_end))
parser.print_help()
@gsw945
Copy link
Author

gsw945 commented Jul 19, 2017

usage example in terminal:

# assign execution permission
chmod a+x ./cat_line.py
  • example 1

    ./cat_line.py /usr/share/mime/types -b 3 -e 5
    # will print from line 3 to line 5 (line: 3, 4, 5)

    output:

    application/atom+xml
    application/dicom
    application/ecmascript
    
  • example 2

    ./cat_line.py /usr/share/mime/types -b 743
    # will print from line 743 to the left all lines of file

    output:

    x-content/video-svcd
    x-content/video-vcd
    x-content/win32-software
    x-epoc/x-sisx-app
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment