如何使用parse_known_args返回的命名空间?

Sha*_*leh 5 python parsing replace

我目前正在编写Python脚本并尝试动态生成一些参数.但是,以下脚本会引发错误,说明'Namespace' object is not iterable.有关如何修复的任何想法?

import argparse
from os import path
import re

replacements = {}
pattern = '<<([^>]*)>>'

def user_replace(match):
   ## Pull from replacements dict or prompt
    placeholder = match.group(1)
    return (replacements[placeholder][0] 
         if placeholder in replacements else 
          raw_input('%s? ' % placeholder))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('outfile', type=argparse.FileType('w'))

    required, extra = parser.parse_known_args()
    infile, outfile = required.infile, required.outfile
    args = re.findall(pattern, infile.read())
    args = list(set(args))
    infile.seek(0)

    parser = argparse.ArgumentParser()
    for arg in args:
        parser.add_argument('--' + arg.lower())

    replacements = vars(parser.parse_args(extra))

    matcher = re.compile(pattern)

    for line in args.infile:
        new_line = matcher.sub(user_replace, line)
        args.outfile.write(new_line)

    args.infile.close()
    args.outfile.close()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

错误与parser.parse_known_args()的返回值有关.关于如何绕过这个的任何想法?有人建议创建一个对象并使用dict接口,但我不知道这究竟是什么.我是Python的新手,所以我不明白为什么(infile,outfile),extra = parser.parse_known_args()不起作用.

编辑:更新了两个修复程序.首先使用下面接受的答案修复上面的错误.其次,还修复了一个错误,我被标记为尝试两次添加相同的参数.通过将args设置为一组然后返回列表来修复.现在我的脚本运行,但可选参数无效.有任何想法吗?

Gar*_*ees 11

ArgumentParser.parse_known_args返回命名空间和剩余参数的列表.命名空间不可迭代,因此当您尝试将一个命名空间分配给元组时,(infile, outfile)您会收到"不可迭代"错误.

相反,你应该写一些类似的东西

namespace, extra = parser.parse_known_args()
Run Code Online (Sandbox Code Playgroud)

然后以namespace.infile和的方式访问已解析的参数namespace.outfile.


Nil*_*Nil 5

我对 parse_args() 方法也有类似的问题。我想将名称空间用作字典。既然它看起来像一个字典,那应该是可能的!

args = parser.parse_args()
for k, v in args: -> "'Namespace' object is not iterable."
for k, v in dict(args): -> "'Namespace' object is not iterable."

for k, v in args.__dict__.iteritems():
    print(k, v) # Works!

# Or just use it as any other dictionary
d.update(args.__dict__)
f(**args.__dict__)
Run Code Online (Sandbox Code Playgroud)

  • `vars()` 是将对象的属性转换为字典的规范方法...... (2认同)