问题描述
在未指定任何参数的情况下,我的脚本应启动演示模式.我试过了:
My script should start a demo mode, when the no parameters are given. I tried this:
args = parser.parse_args()
if len(args) == 0:
run_demo()
else:
# evaluate args
哪个给出*** TypeError: object of type 'Namespace' has no len()
,因为args
没有列表.
Which gives a *** TypeError: object of type 'Namespace' has no len()
as args
is no list.
我将如何实现我想要的?
How would I achieve what I want?
推荐答案
如果您的目标是检测何时未为命令提供无参数,那么通过argparse
进行操作是错误的方法(如Ben所指出的那样).
If your goal is to detect when no argument has been given to the command, then doing this via argparse
is the wrong approach (as Ben has nicely pointed out).
想想简单! :-)我相信argparse不会使sys.argv
人口减少.因此,if not len(sys.argv) > 1
,则用户未提供任何参数.
Think simple! :-) I believe that argparse does not depopulate sys.argv
. So, if not len(sys.argv) > 1
, then no argument has been provided by the user.
这篇关于Argparse:检查是否已传递任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!