【发布时间】:2016-04-05 06:35:11
【问题描述】:
我正在使用 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']
我没有尝试从该列表中提取(文件,输出到文本文件)和(帮助,显示此帮助消息并退出),但发现很难解析它们。对此有何意见?
【问题讨论】:
-
这与您之前的问题stackoverflow.com/questions/36380688/… 有何不同?在那个你可以访问
parser对象。在这里你只能访问help消息吗? -
@hpaulj 我实际上不想更改该脚本中的代码。我正计划编写一个新脚本来读取此输出文件并解析参数数据。
-
我认为您只需要自己解析文本即可。
-
@hpaulj 有没有办法读取这个文件,使用 rstrip()、search() 并提取这些术语?我正在尝试类似的方法,但无法完全提取它。