【问题标题】:Extract argument parameters from argparse output从 argparse 输出中提取参数参数
【发布时间】: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() 并提取这些术语?我正在尝试类似的方法,但无法完全提取它。

标签: python argparse


【解决方案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'等中提取'file'。

【讨论】:

  • 到目前为止,我已经用我的代码和输出编辑了这个问题。我得到了一个值列表,但需要对其进行解析以提取这两个字段。
  • 您的行仍然可以在 ' +' 上分割 - 2 个或更多空格。此外,optionals 帮助应该与positionals 帮助一致。因此,您可以使用标识“帮助”缩进的那个。
猜你喜欢
  • 1970-01-01
  • 2016-06-19
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2021-09-02
  • 2014-08-02
  • 1970-01-01
相关资源
最近更新 更多