-
Notifications
You must be signed in to change notification settings - Fork 4
/
grep.py
61 lines (37 loc) · 972 Bytes
/
grep.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python3
"""------------------------------------------------------------
Esse programa e um simulador basico do comando grep do UNIX
Programa 3 do curso de Python e Django.
------------------------------------------------------------"""
#Importacao
import sys
FOUND = 0
NOT_FOUND = 1
ERROR = 2
def find(search, filename):
__file = open(filename)
for line in __file:
if search in line:
yield line.strip()
__file.close()
def main(args):
try:
search = args[1]
except IndexError:
print >>sys.stderr,("Usage: grep [OPTION]... PATTERN [FILE]...")
return(ERROR)
filenames = args[2:]
ret = NOT_FOUND
#iteracao
for filename in filenames:
try:
for line in find(search, filename):
print("%s:%s" % (filename, line))
ret = FOUND
except IOError, ex:
print >>sys.stderr,("grep.py: %s: %s" %(ex.filename, ex.strerror))
return(ERROR)
return(ret)
args = sys.argv
ret = main(args)
sys.exit(ret)