我正在使用argparse庫在我的腳本中使用不同的參數。我將以下結果的輸出傳遞給result.txt文件。從argparse輸出中提取參數參數
我有一個表名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']
我不是想提取(文件,輸出到文本文件),(幫助,顯示此幫助消息並退出),但發現很難解析它們。對此有何意見?
是如何從你前面的問題這個不同,http://stackoverflow.com/questions/提取「文件」 36380688 /提取物的值從 - 解析加參數的功能於argparse-蟒?在那一箇中你可以訪問'parser'對象。你在這裏只能訪問「幫助」信息嗎? – hpaulj
@hpaulj我其實不想更改該腳本中的代碼。我打算寫一個新的腳本來讀取這個輸出文件並解析參數數據。 –
我認爲你只需要爲自己解析文本。 – hpaulj