Argparse:检查是否传递了任何参数 [英] Argparse: Check if any arguments have been passed
问题描述
当没有给出参数时,我的脚本应该启动演示模式.我试过这个:
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 执行此操作code> 是错误的方法(正如 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:检查是否传递了任何参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!