【问题标题】:Python argparse: Does it have to return a list?Python argparse:它是否必须返回一个列表?
【发布时间】:2023-03-18 00:16:01
【问题描述】:

我正在尝试从 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 参数”时程序会失败,但在我提供时可以正常工作。

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

我该如何解决这个问题?

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    不要尝试连接None"hi "

    print("hi", test)
    

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

    或测试test 是否明确设置为无:

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

    【讨论】:

      【解决方案2】:

      与无比较时使用“是”。应该是这样的:

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

      【讨论】:

        【解决方案3】:

        关于标题的问题,当使用nargs时,args.n的返回值是一个列表(即使使用了nargs=1)。因此,当只需要 1 个参数时,您可能决定根本不使用 nargs 以避免返回列表。

        import argparse
        parser = argparse.ArgumentParser()
        parser.add_argument('-n')
        args = parser.parse_args()
        test = args.n
        if test:
            print("hi " + test) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-23
          • 1970-01-01
          • 1970-01-01
          • 2019-01-17
          • 1970-01-01
          • 2023-01-16
          • 2023-03-24
          • 1970-01-01
          相关资源
          最近更新 更多