【问题标题】:Overwrite a default argument with another one using the command line使用命令行用另一个参数覆盖默认参数
【发布时间】:2021-05-05 11:57:00
【问题描述】:

谁能帮我用另一个通过命令行的参数覆盖默认参数? 这是我的代码:

parser = argparse.ArgumentParser()
parser.add_argument('log', action='store', help='path to the log file')
parser.add_argument('-f', '--filter', default =['filter.json'], help='path to a filter file')
parser.add_argument('-w', '--waiver', type =list, default = [], action='append', help='path to a waiver file')
args = parser.parse_args()

这是要使用的命令行:

python3 script.py -f filter_file -w waiver_file log_file

所以,我需要用 filter_file 覆盖这个 default =['filter.json']

但是不知道该怎么办,请大家支持一下吗?

谢谢

【问题讨论】:

  • 您显示的代码有什么问题?看起来它可以做你想做的事。

标签: python python-3.x scripting


【解决方案1】:

您的脚本正在运行: 我的输出:

PS C:\Users\xf01145\Documents\Python> & "C:/Program Files/Python37/python.exe"

c:/Users/xf01145/Documents/Python/cli.py log.log -f bla.bla blubb.bla test.test hugo.txt
Namespace(filter=['bla.bla', 'blubb.bla', 'test.test', 'hugo.txt'], log='log.log', waiver=[])
0 bla.bla
1 blubb.bla
2 test.test
3 hugo.txt
PS C:\Users\xf01145\Documents\Python>

从此:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('log', action='store', help='path to the log file')
parser.add_argument('-f', '--filter', default =['filter.json'], help='path to a filter file',  nargs='+')
parser.add_argument('-w', '--waiver', type =list, default = [], action='append', help='path to a waiver file')
args = parser.parse_args()

print(args)

for i,item in enumerate(args.filter):
    print(i, item)

【讨论】:

  • 似乎工作,但我在尝试做类似的事情时仍然面临一个问题:对于过滤器中的元素(过滤器列表的元素)做一些事情,它将该列表作为返回此错误的字符串“没有这样的文件或目录 f " 所以 f 是 filter_file name 中的第一个字母
  • 您有一个过滤器文件,还是要添加一个或多个文件?
  • 希望有可能添加更多
  • 我编辑了我的解决方案帖子。希望这是您想要的。
  • 是的,但是默认的 filter_file 仍然没有被覆盖
猜你喜欢
  • 2012-10-13
  • 1970-01-01
  • 2019-09-09
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多