2013-03-13 30 views
1

我想从argparse中获得一串数字。是否提供参数-n是可选的。Python argparse:它是否必须返回一个列表?

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参数”时程序失败,但是当我这样做的时候工作正常。

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 

我该如何解决这个问题?

回答

2

不要试图串联None"hi "

print("hi", test) 

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

或测试,如果test设置为无明确:

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

用途 “是” 的时候与无比较。应该看起来像这样:

if test is not None: 
    print("hi %s" % test) 
相关问题