Python argparse:它必须返回一个列表吗? [英] Python argparse: Does it have to return a list?
本文介绍了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
我该如何解决这个问题?
How can I fix this?
推荐答案
不要尝试连接 None
和 "hi "
:
Do not try to concatenate None
and "hi "
:
print("hi", test)
或
print("hi " + (test or ''))
或测试 test
是否显式设置为 None:
or test if test
is set to None explicitly:
if test is not None:
print("hi", test)
这篇关于Python argparse:它必须返回一个列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文