【发布时间】: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