gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:05 24 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于Python 将多个字符串传递给单个命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com