[Tutor] optparse
Matt Herzog
msh at blisses.org
Tue Dec 23 21:10:29 CET 2008
Hi All.
I want to write a script that will emulate grep to some extent. This is just an exercise for me. I want to run the script like this:
./pythongrep directory searchstring
Just like grep, I want it to print: filename, instance_of_match
As of now, the script can't find anything I tell it to look for. It prints, "None." Thanks for any advice.
import optparse
import os
import re
def main():
p = optparse.OptionParser(description="Python grepper", prog="greppar", version="0.1", usage="usage: %prog directory regex")
options, arguments = p.parse_args()
if len(arguments) == 2:
directory = arguments[0]
regex = arguments[1]
s = re.compile(regex)
for filename in os.listdir(directory):
result = re.match(s, filename)
print result
else:
p.print_help()
if __name__ == '__main__':
main()
--
I fear you speak upon the rack,
Where men enforced do speak anything.
- William Shakespeare
More information about the Tutor
mailing list