[Tutor] receiving regular expression from command line
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Oct 1 12:42:40 EDT 2016
On 01/10/16 09:16, anish singh wrote:
> I am trying to implement grep to just increase my knowledge
> about regular expression.
>
> Below is the program usage:
> python test.py -i Documents/linux/linux/ -s '\w+_readalarm*'
>
> However, due to my lack of knowledge about string handling
> in python, I am getting wrong results.
Possibly, but we can't tell because
a) You don't show us the code that parses your input
b) You don't show us your output/error message
How are you parsing the input? Are you using
the argparse module? Or one of the older ones?
Or are you trying to just test the values in sys.argv?
How do you determine the input filename and the pattern?
Have you proved that those values are correct before you
call your read_file() function?
> def read_file(file, pattern):
> with open(file, 'r') as outfile:
Since you are reading it it probably should be
called infile?
> for line in outfile:
> match = re.compile(str(pattern)).match(line)
> if match:
> print(file + " " + match.group())
> Can someone let me know how can I pass regular expression
> from command line?
The real issue here is probably how you parse the
input line but we can't tell. The recommended module
for doing that is argparse. Try reading the module
documentation which includes many examples.
If you are still having problems show us your full
program plus any error messages
> Whole code: http://ideone.com/KxLJP2
Unless its very long (>100lines?) just post it
in your email.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list