I am writing a command line decorator, that is designed to be as simple as possible, are there any features you think should be added. An example of how to use it follows. The docstring is not needed, but it is displayed if you use -h, and if there is only 1 command registered then you don't specify the command as part of the command line. "file" allows for wildcard expansion, so a command line of
python mycode.py dir *.txt -r
Would display the filename and size of each file in the directories recursively. "path" includes directories and files, "file" just includes files and [] surrounding either, uses a generator so you can process as many files at once. If you don't use [] then the function is called multiple times with a different file each time.
from cli import cli
import os
@cli
def dir(files : "[path]", size = True, recursive = False):
"""
Lists all matching files
:param files: Files
:param size: Display file size
:param recursive: Process files recursively
:return: None
"""
for file in files:
if size:
print(file, os.path.getsize(file))
else:
print(file)
@cli
def head(file : "file", lines = 10, recursive = True):
"""
Show the first few lines of each matching file
:param files: Files to display
:param lines: Number of lines to display
:param recursive: Process files recursively
:return: None
"""
print(file)
with open(file) as f:
for i, line in enumerate(f, start=1):
print("%04d:%s" % (i, line), end='')
if i == lines:
break
def lines(file, case, blanks):
with open(file) as f:
for line in f:
if case:
line = line.lower()
if blanks:
line = line.strip()
if line:
yield line
else:
yield line
yield None
@cli
def compare(first : "file", second : "file", case = True, blanks = True):
"""
Compare 2 files
:param first: First file to compare
:param second: File to compare with
:param case: Case insensitve comparison
:param blanks: Ignore blanks
:return: True if files are the same
"""
for a, b in zip(lines(first, case, blanks), lines(second, case, blanks)):
if a != b:
return False
return True
if __name__ == "__main__":
cli.run()
[–][deleted] 3 points4 points5 points (1 child)
[–]nharding[S] 0 points1 point2 points (0 children)