本文介绍了Argparse:检查是否已传递任何参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在未指定任何参数的情况下,我的脚本应启动演示模式.我试过了:

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:检查是否已传递任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 04:24