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

Python pass multiple strings to a single command line argument

我是 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"。我尝试按照以下方式传递多个文件名,但 none 有效。

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 位)

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

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

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

从您发布的所有内容来看,您的代码看起来很可靠。

问题出在您发布的应该遍历列表的片段上。您的程序设置方式不能将 infile 用作变量

修复它所需要做的就是将 infile 切换为 options.infile

具体来说:

 for filename in options.infile:
    print(filename)

这是因为您所有的参数都存储在选项 "Namespace" 类型的变量中