对于我的程序,我需要解析一个.xml文件和一个.ttf文件。我不想通过键入参数的id来打扰用户,但我宁愿接受解析的数据,然后决定哪个文件基于.extension。是否有可能与argparser做类似的事情
py -3 file.py "C/documents/file.xml" "C/documents/font.ttf"
以未知顺序并在收到文件路径后决定?我只需要知道如何在没有中断的情况下将这些信息解析到Python程序中。谢谢
在收到用户的输入后,假设他们的路径在var1
和var2
,只需使用var1.split(".")[1]
和var2.split(".")[1]
检查扩展(他们返回点后面的字符串,这是你的文件扩展名)并做这样的事情(假设用户没有放两个具有相同扩展名的文件)
if var1.split(".")[1] == "xml"
xml_file=var1
ttf_file=var2
else:
xml_file=var2
ttf_file=var1
感谢Ralf根据我的问题发表评论,我得到了解决方案
args = sys.argv[1:] #the first one is path of your python script
if len(args) > 3:
print('wrong')
for i in args:
if i.endswith('.xml'):
xml_path = i
if i.endswith('.ttf'):
font_path = i
您可以使用自定义操作。对delattr
的调用对我来说感觉有些不确定,但保持名称空间清洁。
class InputFileAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if values.endswith(".ttf"):
dest = "ttf_file"
elif values.endswith(".xml"):
dest = "xml_file"
else:
raise argparse.ArgumentTypeError("File must have .ttf or .xml extension")
setattr(namespace, dest, values)
delattr(namespace, self.dest)
p = argparse.ArgumentParser()
p.add_argument("input1", action=InputFileAction)
p.add_argument("input2", action=InputFileAction)
一些例子:
>>> p.parse_args(["foo.ttf", "foo.xml"])
Namespace(ttf_file='foo.ttf', xml_file='foo.xml')
>>> p.parse_args(["foo.xml", "foo.ttf"])
Namespace(ttf_file='foo.ttf', xml_file='foo.xml')