我正在使用argparse库在我的脚本中使用不同的参数。我将以下结果的输出传递给result.txt文件。
我有一个表名test_arguments,我需要存储不同的参数名称和描述。以下示例我需要插入:
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) ;
如何读取此文件并从下面的“result.txt”文件中提取这两个字段?哪种方法最好?
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
更新:我的代码
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)
输出:
num The fibnocacci number to calculate:
['-h, --help show this help message and exit', '-f, --file Output to the text file']
我没有尝试从此列表中提取(文件,输出到文本文件)和(帮助,显示此帮助消息并退出),但发现难以解析它们。对此有任何意见吗?
答案 0 :(得分:1)
这是解析帮助文本的开始
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()
看起来有2个空格区分help
行。我必须检查formatter
代码,但我认为有尝试排列help
文本,并清楚地将它们分开。
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']
使用re.split
比使用字符串split
方法更容易基于2个或更多空格拆分行。事实上,我可能已经使用re
来收集arglines
。我也可以检查参数组名称(positional arguments
等)。
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']]
现在我只需要提取文件'来自' -f, - file'等