gpt4 book ai didi

Python argparse : Does it have to return a list?

转载 作者:行者123 更新时间:2023-11-30 23:37:36 24 4
gpt4 key购买 nike

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

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 参数”时,程序会失败,但当我提供“-n 参数”时,程序运行良好。

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”:

print("hi", test)

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

或者测试test是否显式设置为None:

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

关于Python argparse : Does it have to return a list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15393672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com