Python argparse: Does it have to return a list?

百般思念 提交于 2019-12-24 12:38:25

问题


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) 

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?


回答1:


Do not try to concatenate None and "hi ":

print("hi", test)

or

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

or test if test is set to None explicitly:

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



回答2:


Use "is" when comparing to None. Should look like this:

if test is not None:
    print("hi %s" % test) 


来源:https://stackoverflow.com/questions/15393672/python-argparse-does-it-have-to-return-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!