Ejercicio 7

This commit is contained in:
perro tuerto 2023-02-20 18:05:21 -08:00
parent f65c9a0a7c
commit 8bdf5a21d2
1 changed files with 59 additions and 0 deletions

59
exercises/ex07/ex07.py Normal file
View File

@ -0,0 +1,59 @@
# Exercise 2
# 1. grep command
import re
import sys
import argparse
from pathlib import Path
def loop(args):
stderr = False
for path in args["paths"]:
if not path.exists():
print(f"grep: {path}: No existe el fichero o el directorio")
stderr = True
elif path.is_dir():
print(f"grep: {path}: Es un directorio")
stderr = True
else:
grep(path, args)
return stderr
def grep(path, args):
lines = open(path, "r").readlines()
res = []
pre = ""
if len(args["paths"]) > 1:
pre = f"{path}:"
for line in lines:
tmp = line[:]
if args["ignore_case"]:
tmp = tmp.lower()
if args["extended_regexp"]:
res = re.compile(args["extended_regexp"]).search(tmp)
else:
res = tmp.find(args["query"])
if res is not None and res != -1:
print(f"{pre}{line}", end="")
parser = argparse.ArgumentParser()
parser.add_argument('paths', nargs="+", type=Path)
parser.add_argument('-i', '--ignore-case', default=False, action="store_true")
parser.add_argument('-E', '--extended-regexp', default=False, type=str)
if len(sys.argv) > 1:
if sys.argv[1] != "-E" and sys.argv[1] != "-i":
query = str(sys.argv[1])
del sys.argv[1]
else:
query = False
args = parser.parse_args().__dict__
args["query"] = query
stderr = loop(args)
if stderr:
sys.exit(1)
else:
sys.exit(1)