【问题标题】:How can I write the argument name from Python argparse to a file?如何将 Python argparse 中的参数名称写入文件?
【发布时间】:2016-07-23 12:22:11
【问题描述】:

我想使用 argparse 将它接收到的参数名称和值写入文件。到目前为止我有这个:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--infile", help = "seed file", default = 'test')
parser.add_argument("--lang", help="wiki language bigram", default = 'en')
parser.add_argument("--request_type", help="request type", default = 'sum')
parser.add_argument("--outfile", help = "path to outfile", default = 'outfile')
parser.add_argument("--summary", help = "true or false", action = "store_true")
parser.add_argument("--pagehits", help = "path to list of page hits", default = 'pagehits')
parser.add_argument("--exemplar_file", help = "file to inspire book")

args = parser.parse_args()

input_file = args.infile
print(args.infile)
print(var(args))

with open('modified-variables', 'w') as outfile:
    outfile.write(args.infile)
    outfile.write('hello world')

with --infile "/path/to/file" --lang "en" 输出为:

/path/to/file
en

[but nothing written to file]

我希望它遍历所有位置参数并将命令行中提供的所有位置参数写入格式中的修改变量

infile="/path/to/file"
lang="en"

谷歌搜索并没有帮助我弄清楚如何打印 argnames,而且 with/write 结构中存在一些简单的错误。

更新:每个答案 #1 添加了 print(vars((args)) 产生:

{'lang': 'en', 'exemplar_file': None, 'pagehits': 'pagehits', 'summary': False, 'outfile': '/tmp/pagekicker/123/out_test', 'request_type': 'sum', 'infile': '/home/fred/pagekicker-community/scripts/seeds/revolutionary-figures'}

现在我只想写

lang="zh" exemplar_file="无"

等等

到一个文件。

【问题讨论】:

  • 你为什么要给parse_args打两次电话?
  • 这是一个错误,已修复

标签: python argparse with-statement


【解决方案1】:

你试过了吗

print(args)    # the default Namespace display format

print(vars(args))

vars(args) 是一个字典,您可以以多种不同的方式显示它。您可以将其转换为元组列表 (.items()),也可以遍历 keys,等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 2021-06-28
    • 1970-01-01
    • 2018-07-24
    • 2016-06-21
    • 2023-02-06
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多