Python argparse:是否必须返回列表? [英] Python argparse: Does it have to return a list?

查看:76
本文介绍了Python argparse:是否必须返回列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从argparse获取一串数字.是否提供参数-n是可选的.

I am trying to obtain a string of numbers from argparse. It's optional whether or not the argument -n is provided.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-n', nargs=1) # -n is optional but must come with one and only one argument
args = parser.parse_args()
test = args.n
if test != 'None':
    print("hi " + test) 

当我不提供"-n参数"时,程序将失败,但是当我提供时,它将运行正常.

The program fails when I do not provide "-n argument", but works fine when I do.

Traceback (most recent call last):
  File "parse_args_test.py", line 7, in <module>
    print("hi " + test) 
TypeError: Can't convert 'NoneType' object to str implicitly

我该如何解决?

推荐答案

请勿尝试将None"hi "连接起来:

Do not try to concatenate None and "hi ":

print("hi", test)

print("hi " + (test or ''))

或测试是否将test显式设置为无":

or test if test is set to None explicitly:

if test is not None:
    print("hi", test)

这篇关于Python argparse:是否必须返回列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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