2016-04-04 14 views
0

我正在使用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'] 

我不是想提取(文件,輸出到文本文件),(幫助,顯示此幫助消息並退出),但發現很難解析它們。對此有何意見?

+0

是如何從你前面的問題這個不同,http://stackoverflow.com/questions/提取「文件」 36380688 /提取物的值從 - 解析加參數的功能於argparse-蟒?在那一箇中​​你可以訪問'parser'對象。你在這裏只能訪問「幫助」信息嗎? – hpaulj

+0

@hpaulj我其實不想更改該腳本中的代碼。我打算寫一個新的腳本來讀取這個輸出文件並解析參數數據。 –

+0

我認爲你只需要爲自己解析文本。 – hpaulj

回答

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() 

看起來像兩個空間區分help線開始。我必須檢查formatter的代碼,但我認爲有人試圖排列help文本,並將它們明確分開。根據2個或多個空格

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方法更容易。事實上,我可能可以使用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」等

+0

我已經使用我的代碼編輯了問題,並輸出到現在。我得到了一個值列表,但需要解析它以提取這兩個字段。 –

+0

您的線條仍然可以在「+」分隔 - 2個或更多空格。另外'optionals'幫助應該與'positionals'幫助保持一致。所以你可以使用標識'幫助'縮進的標識。 – hpaulj