Python将多个字符串传递给单个命令行参数

时间:2016-04-19 01:16:41

标签: python list python-3.x command-line-arguments traversal

我是Python的新手,几乎不了解列表和元组。我有一个要执行的程序,它接受几个值作为输入参数。以下是输入参数列表

parser = argparse.ArgumentParser()
parser.add_argument("server")
parser.add_argument("outdir")
parser.add_argument("dir_remove", help="Directory prefix to remove")
parser.add_argument("dir_prefix", help="Directory prefix to prefix")
parser.add_argument("infile", default=[], action="append")
options = parser.parse_args()

使用以下命令

可以正常运行该程序
python prod2dev.py mysrv results D:\Automations D:\MyProduction Automation_PP_CVM.xml

但是看一下代码,似乎代码可以为参数“infile”接受多个文件名。我试过跟随传递多个文件名但没有工作。

python prod2dev.py mysrv results D:\Automations D:\MyProduction "Automation_PP_CVM.xml, Automation_PT_CVM.xml"

python prod2dev.py mysrv results D:\Automations D:\MyProduction ["Automation_PP_CVM.xml", "Automation_PT_CVM.xml"]

python prod2dev.py mysrv results D:\Automations D:\MyProduction ['Automation_PP_CVM.xml', 'Automation_PT_CVM.xml']

python prod2dev.py mysrv results D:\Automations D:\MyProduction ['"Automation_PP_CVM.xml"', '"Automation_PT_CVM.xml"']

下面的代码显然是遍历列表

infile = windowsSucksExpandWildcards(options.infile)
 for filename in infile:
    print(filename)
    outfilename = os.path.join(options.outdir, os.path.split(filename)[1])
    if os.path.exists(outfilename):
        raise ValueError("output file exists: {}".format(outfilename))

    with open(filename, "rb") as f:
        root = lxml.etree.parse(f)
    if not isEnabled(root):
        print("Disabled. Skipping.")
        continue
    elif not hasEnabledTriggers(root):
        print("Has no triggers")
        continue
...
...
...
def windowsSucksExpandWildcards(infile):
    result = []
    for f in infile:
        tmp = glob.glob(f)
        if bool(tmp):
            result.extend(tmp)
        else:
            result.append(f)
    return result

请指导如何将多个文件名(字符串)传递给单个参数“infile”,这显然是一个列表。

我正在运行Python 3.5.1 | Anaconda 4.0.0(32位)

2 个答案:

答案 0 :(得分:5)

您传递了nargs参数,而不是action="append"

parser.add_argument("infile", default=[], nargs='*')

*表示零或更多,就像在正则表达式中一样。 如果您需要至少一个,也可以使用+。由于您有默认值,我假设用户不需要传递任何默认值。

答案 1 :(得分:0)

您发布的所有代码看起来都很稳定。

问题在于您发布了应该遍历列表的片段。您的程序设置方式无法使用infile作为变量

要解决此问题,只需使用infile

切换options.infile即可

具体做法是:

 for filename in options.infile:
    print(filename)

原因是你的所有参数都存储在选项“Namespace”-type variable

相关问题