结合使用argparser和给用户​​的问题 [英] Using argparser in combination with questions to the user

查看:59
本文介绍了结合使用argparser和给用户​​的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图通过 argparse 使我的代码可用,但是我希望大多数用户不太熟悉在控制台中运行某些内容.是他们通过问题请求输入的一种方式.

so I am trying to make my code usable though argparse but I am expecting that most users are not so familiar with running something in a console. Is their a way that I would request the input through questions.

赞:

Please provide the path to the data:
/home/usr/...

What is the target variable? 
y

以此类推,甚至可以使用 argparser 还是我应该寻找其他东西

And so on, is that even possible with argparser or should I look for something else

推荐答案

argparse 仅提供命令行参数,并且不支持提示用户,但是它确实使实现类似这样的操作变得容易.它支持可选参数,并且在解析后为您提供了可以使用的名称空间对象.您只需要实现自己的提示并分配给名称空间即可.

argparse only does command line arguments and doesn't support prompting the user, but it does make it easy to implement something like this. It supports optional arguments, and after parsing gives you a namespace object you can use. You just need to implement the prompting yourself and assign into the namespace.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('path', nargs='?')
parser.add_argument('target', nargs='?')
args = parser.parse_args()

print(args)

if args.path is None:
    args.path = input('Please provide the path to the data: ')

if args.target is None:
    args.target = input('What is the target variable? ')

print(args)

测试运行:

$ ./test.py /somepath spam  # All arguments provided
Namespace(path='/somepath', target='spam')
Namespace(path='/somepath', target='spam')

$ ./test.py /otherpath  # Forgotten "target"
Namespace(path='/otherpath', target=None)
What is the target variable? eggs
Namespace(path='/otherpath', target='eggs')

$ ./test.py  # No arguments provided
Namespace(path=None, target=None)
Please provide the path to the data: /anotherpath
What is the target variable? ham
Namespace(path='/anotherpath', target='ham')

如果您有两个以上的参数,我建议将上面的代码干燥掉,像这样:

If you have more than two parameters I'd recommend DRYing out the above code, something like this:

arg_prompts = [
    ('path', 'Please provide the path to the data: '),
    ('target', 'What is the target variable? '),
    ]

for arg, prompt in arg_prompts:
    if getattr(args, arg) is None:
        setattr(args, arg, input(prompt))

这篇关于结合使用argparser和给用户​​的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆