结合使用 argparser 向用户提问 [英] Using argparser in combination with questions to the user
问题描述
所以我试图通过 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屋!