【问题标题】:parse a path like and an argument解析路径和参数
【发布时间】:2019-01-13 09:28:24
【问题描述】:

我在 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

我不知道如何将输出存储到变量中。 我该如何继续?

【问题讨论】:

  • 您想将哪个输出存储到变量中?当你调用--help时这个程序的输出?程序本身的输出?命令行输入?除非您更具体地说明您需要我们做什么,否则我认为我们无法提供帮助。
  • 我想将我给程序的路径存储到一个变量中 python script.py -o C:/Users/michael/Documents/install -a all -p windows, C:/当我运行程序时将用户/迈克尔/文档/安装存储到变量中

标签: python python-3.x file path argparse


【解决方案1】:

在您的情况下,您可以使用以下方法访问参数:

正如您在评论中所建议的那样,您只想访问 --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

【讨论】:

  • 我这样做了,实际上我只是想在运行程序时将参数“C:/Users/michael/Documents/install”存储到变量中,这就是例子: -o C:/Users/michael/Documents/install -a all -p windows
  • 然后只使用我的示例中的第三行,我在其中创建了一个变量输出,这应该适合你
【解决方案2】:

您可以使用vars(args) 获取传递的参数的字典。 args.parse_args() 返回 Namespace object,然后您可以在其上使用 vars(args) 以获取字典。使用https://docs.python.org/3/tutorial/datastructures.html 了解如何操作字典。
如果您不想了解 dicts 或想保持简单,其他答案可能会更好:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 2021-08-22
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多