解析类似路径和参数
parse a path like and an argument
我在 python 3.7:
中有这个脚本
pars = argparse.ArgumentParser(prog='copy dirs script', description="à copier MSRE localment:",
epilog="Comme ça on copie les repertoires")
pars.add_argument("-o", "--output", action='store_const', default=destination_file,
const=destination_file1,
help="the destination dirctory is the curently working dirctory")
pars.add_argument("-a", "--arch", choices=("all", "i386", "x86_64"), type = lambda s : s.lower(),
help="Targeted check architecture: 32b, 64b, All")
pars.add_argument("-p", "--platform", choices=("all", "windows", "linux"), type = lambda s : s.lower(),
help="Targeted check platform: Windows, Linux, All")
args = pars.parse_args()
我想解析命令行中的输出,例如:
python script.py -o C:/Users/michael/Documents/install -a all -p windows
我不知道如何将输出存储到变量中。
我该如何继续?
您可以通过使用 vars(args)
获取传递的参数的字典。 args.parse_args()
returns a Namespace object and you can then use vars(args)
on it in order to get a dictionary. Use https://docs.python.org/3/tutorial/datastructures.html 了解如何操作字典。
如果您不想了解字典或不想让它简单一些,其他答案可能会更好:)
在您的情况下,您可以使用以下方式访问参数:
正如您在评论中所建议的那样,您想要的只是访问 --output 或 -o 将您的 add_argument 更改为输出到我在下面添加的东西
pars.add_argument("-o", "--output", default=destination_file,
help="the destination dirctory is the curently working dirctory")
platform = args.platform
architecture = args.arch
output = args.output
依此类推,您要访问的任何其他参数都应该在 args 变量中可用。浏览文档以获取更多信息
Documentation
我在 python 3.7:
中有这个脚本pars = argparse.ArgumentParser(prog='copy dirs script', description="à copier MSRE localment:",
epilog="Comme ça on copie les repertoires")
pars.add_argument("-o", "--output", action='store_const', default=destination_file,
const=destination_file1,
help="the destination dirctory is the curently working dirctory")
pars.add_argument("-a", "--arch", choices=("all", "i386", "x86_64"), type = lambda s : s.lower(),
help="Targeted check architecture: 32b, 64b, All")
pars.add_argument("-p", "--platform", choices=("all", "windows", "linux"), type = lambda s : s.lower(),
help="Targeted check platform: Windows, Linux, All")
args = pars.parse_args()
我想解析命令行中的输出,例如:
python script.py -o C:/Users/michael/Documents/install -a all -p windows
我不知道如何将输出存储到变量中。 我该如何继续?
您可以通过使用 vars(args)
获取传递的参数的字典。 args.parse_args()
returns a Namespace object and you can then use vars(args)
on it in order to get a dictionary. Use https://docs.python.org/3/tutorial/datastructures.html 了解如何操作字典。
如果您不想了解字典或不想让它简单一些,其他答案可能会更好:)
在您的情况下,您可以使用以下方式访问参数:
正如您在评论中所建议的那样,您想要的只是访问 --output 或 -o 将您的 add_argument 更改为输出到我在下面添加的东西
pars.add_argument("-o", "--output", default=destination_file,
help="the destination dirctory is the curently working dirctory")
platform = args.platform
architecture = args.arch
output = args.output
依此类推,您要访问的任何其他参数都应该在 args 变量中可用。浏览文档以获取更多信息 Documentation