2013-03-13 96 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) 
相關問題