Reputation: 1367
I am using argparse library to use different arguments in my script. I am passing the output of the below result to the result.txt file.
I have a table name test_arguments where i need to store different argument name and description. example from below i need to insert :
Insert into table test_argument ( arg_name, arg_desc ) as ( num, The fibnocacci number to calculate:);
Insert into table test_argument ( arg_name, arg_desc ) as ( help, show this help message and exit) ;
Insert into table test_argument ( arg_name, arg_desc ) as ( file, output to the text file) ;
How can i read this file and extract these two fields from the below 'result.txt' file? Which is the best way to do it?
python sample.py -h >> result.txt
result.txt
-----------
usage: sample.py [-h] [-f] num
To the find the fibonacci number of the give number
positional arguments:
num The fibnocacci number to calculate:
optional arguments:
-h, --help show this help message and exit
-f, --file Output to the text file
Updated : My code
import re
list = []
hand = open('result.txt','r+')
for line in hand:
line = line.rstrip()
if re.search('positional', line) :
line = hand.readline()
print(line)
elif re.search('--',line):
list.append(line.strip())
print(list)
Output :
num The fibnocacci number to calculate:
['-h, --help show this help message and exit', '-f, --file Output to the text file']
I am not trying to extract (file,Output to the text file) and (help,show this help message and exit) from this list but finding it difficult to parse them. Any inputs on this?
Upvotes: 0
Views: 174
Reputation: 231355
Here's a start at parsing your help text
In [62]: result="""usage: sample.py [-h] [-f] num
To the find the fibonacci number of the give number
positional arguments:
num The fibnocacci number to calculate:
optional arguments:
-h, --help show this help message and exit
-f, --file Output to the text file"""
In [63]: result=result.splitlines()
Looks like 2 spaces distinguishes the help
lines. I'd have to check the formatter
code, but I think there is an attempt to line up the help
texts, and clearly separate them.
In [64]: arglines=[line for line in result if ' ' in line]
In [65]: arglines
Out[65]:
['num The fibnocacci number to calculate:',
'-h, --help show this help message and exit',
'-f, --file Output to the text file']
Splitting lines based on 2 or more spaces is easier with re.split
than the string split
method. In fact I probably could have used re
to collect arglines
. I could also have checked for the argument group names (positional arguments
etc).
In [66]: import re
In [67]: [re.split(' +',line) for line in arglines]
Out[67]:
[['num', 'The fibnocacci number to calculate:'],
['-h, --help', 'show this help message and exit'],
['-f, --file', 'Output to the text file']]
Now I just have to extract 'file' from '-f, --file', etc.
Upvotes: 1